使用 xstream 将 XML 的一部分解组为字符串

发布于 2024-12-15 21:20:59 字数 714 浏览 0 评论 0原文

我正在使用 xstream 来编组/解组 xml。我有以下 xml 片段,我想将节点“rawText”内容作为字符串存储在 Form.java bean 上。

<FormData>

<form id="1">

<rawText>

<h1>All form submitted data goes here</h1>. 
<clob> This can contain more 'xml' like data with more nodes </clob>

</rawText>

</form>

</FormData>

Form.java

class Form{
 private int id;
 private String rawText;

 //getters + setters

}

因此,在上面的示例中,我希望将以下内容填充到 Form bean 上的 rawText 字段中。我该如何实现这一目标?

<h1>All form submitted data goes here</h1>. 
<clob> This can contain more 'xml' like data with more nodes </clob>

I am using xstream to marshal/unmarshal xml. I have following xml fragment for which I would like to store the node 'rawText' contents as a string on Form.java bean.

<FormData>

<form id="1">

<rawText>

<h1>All form submitted data goes here</h1>. 
<clob> This can contain more 'xml' like data with more nodes </clob>

</rawText>

</form>

</FormData>

Form.java

class Form{
 private int id;
 private String rawText;

 //getters + setters

}

So in above example, I would like to get following content populated into rawText field on Form bean. How do I achieve this?

<h1>All form submitted data goes here</h1>. 
<clob> This can contain more 'xml' like data with more nodes </clob>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

薔薇婲 2024-12-22 21:20:59

据我所知,您应该构建一个自定义转换器并处理 reader.getValue() 来连接您的文本,因为它不会按您想要的方式返回整个文本。
检查以下代码,大部分借自 这个问题

转换器:

public class FormConverter implements Converter {

    @SuppressWarnings("rawtypes")
    public boolean canConvert(Class clazz) {
        return Form.class.isAssignableFrom(clazz);
    }

    public void marshal(Object value, HierarchicalStreamWriter writer,
            MarshallingContext context) {
        throw new UnsupportedOperationException("Do the other way around! ;)");
    }

    public Object unmarshal(HierarchicalStreamReader reader,
            UnmarshallingContext context) {
        final Form f = new Form();
        f.setId(Integer.parseInt(reader.getAttribute("id")));

        reader.moveDown();
        if (!"rawText".equals(reader.getNodeName())) {
            throw new ConversionException("Expected rawText, but was "
                    + reader.getNodeName());
        }
        final StringBuilder text = new StringBuilder();
        while (reader.hasMoreChildren()) {
            reader.moveDown();
            buildRecursiveMessage(reader, text);
            reader.moveUp();
        }
        f.setRawText(text.toString());      
        return f;
    }

    private void buildRecursiveMessage(final HierarchicalStreamReader reader,
            final StringBuilder sb) {
        // Build start-tag
        final String nodeName = reader.getNodeName();
        sb.append("<" + nodeName);

        // Build attributes
        final int numAttributes = reader.getAttributeCount();
        if (numAttributes > 0) {
            sb.append(" ");
            for (int i = 0; i < numAttributes; i++) {
                final String attributeName = reader.getAttributeName(i);
                final String attributeValue = reader.getAttribute(i);
                sb.append(attributeName + "=\"" + attributeValue + "\"");

                final boolean lastAttribute = (i == numAttributes - 1);
                if (!lastAttribute) {
                    sb.append(", ");
                }
            }
        }

        // Build children
        final boolean containsChildren = reader.hasMoreChildren();
        final boolean containsValue = !reader.getValue().isEmpty();
        final boolean empty = !containsChildren && !containsValue;

        sb.append(!empty ? ">" : " />");

        if (containsChildren) {
            while (reader.hasMoreChildren()) {
                reader.moveDown();
                buildRecursiveMessage(reader, sb);
                reader.moveUp();
            }
        } else if (containsValue) {
            sb.append(reader.getValue());
        }

        // Build end-tag
        if (!empty) {
            sb.append("</" + nodeName + ">");
        }
    }
}

表单类:

@XStreamConverter(value = FormConverter.class)
public class Form {
    private int id;


    private String rawText;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getRawText() {
        return rawText;
    }

    public void setRawText(String rawText) {
        this.rawText = rawText;
    }

}

仅管理根节点:

public class FormData {
    private Form form;

    public Form getForm() {
        return form;
    }

    public void setForm(Form form) {
        this.form = form;
    }
}

测试:

public static void main(String[] args) {

        XStream xstream = new XStream(new StaxDriver());
        xstream.registerConverter(new FormConverter());
        xstream.alias("FormData", FormData.class);
        FormData f = (FormData) xstream.fromXML(text);
        System.out.println(f.getForm().getRawText());
    }

输出:

<h1>All form submitted data goes here</h1><clob> This can contain more 'xml' like data with more nodes </clob>

再见!

As far as I know you should build up a custom converter and handle the reader.getValue() to concatenate your text, because it does not return the whole text as you want.
Check the following code most borrowed from this question.

Converter:

public class FormConverter implements Converter {

    @SuppressWarnings("rawtypes")
    public boolean canConvert(Class clazz) {
        return Form.class.isAssignableFrom(clazz);
    }

    public void marshal(Object value, HierarchicalStreamWriter writer,
            MarshallingContext context) {
        throw new UnsupportedOperationException("Do the other way around! ;)");
    }

    public Object unmarshal(HierarchicalStreamReader reader,
            UnmarshallingContext context) {
        final Form f = new Form();
        f.setId(Integer.parseInt(reader.getAttribute("id")));

        reader.moveDown();
        if (!"rawText".equals(reader.getNodeName())) {
            throw new ConversionException("Expected rawText, but was "
                    + reader.getNodeName());
        }
        final StringBuilder text = new StringBuilder();
        while (reader.hasMoreChildren()) {
            reader.moveDown();
            buildRecursiveMessage(reader, text);
            reader.moveUp();
        }
        f.setRawText(text.toString());      
        return f;
    }

    private void buildRecursiveMessage(final HierarchicalStreamReader reader,
            final StringBuilder sb) {
        // Build start-tag
        final String nodeName = reader.getNodeName();
        sb.append("<" + nodeName);

        // Build attributes
        final int numAttributes = reader.getAttributeCount();
        if (numAttributes > 0) {
            sb.append(" ");
            for (int i = 0; i < numAttributes; i++) {
                final String attributeName = reader.getAttributeName(i);
                final String attributeValue = reader.getAttribute(i);
                sb.append(attributeName + "=\"" + attributeValue + "\"");

                final boolean lastAttribute = (i == numAttributes - 1);
                if (!lastAttribute) {
                    sb.append(", ");
                }
            }
        }

        // Build children
        final boolean containsChildren = reader.hasMoreChildren();
        final boolean containsValue = !reader.getValue().isEmpty();
        final boolean empty = !containsChildren && !containsValue;

        sb.append(!empty ? ">" : " />");

        if (containsChildren) {
            while (reader.hasMoreChildren()) {
                reader.moveDown();
                buildRecursiveMessage(reader, sb);
                reader.moveUp();
            }
        } else if (containsValue) {
            sb.append(reader.getValue());
        }

        // Build end-tag
        if (!empty) {
            sb.append("</" + nodeName + ">");
        }
    }
}

Form class:

@XStreamConverter(value = FormConverter.class)
public class Form {
    private int id;


    private String rawText;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getRawText() {
        return rawText;
    }

    public void setRawText(String rawText) {
        this.rawText = rawText;
    }

}

Just to manage the root node:

public class FormData {
    private Form form;

    public Form getForm() {
        return form;
    }

    public void setForm(Form form) {
        this.form = form;
    }
}

To test:

public static void main(String[] args) {

        XStream xstream = new XStream(new StaxDriver());
        xstream.registerConverter(new FormConverter());
        xstream.alias("FormData", FormData.class);
        FormData f = (FormData) xstream.fromXML(text);
        System.out.println(f.getForm().getRawText());
    }

Output:

<h1>All form submitted data goes here</h1><clob> This can contain more 'xml' like data with more nodes </clob>

See you!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文