使用xstream将XML解组为String

时间:2011-11-15 18:16:52

标签: xml marshalling xstream unmarshalling

我正在使用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>

1 个答案:

答案 0 :(得分:0)

据我所知,你应该建立一个自定义转换器并处理reader.getValue()来连接你的文本,因为它不会返回你想要的整个文本。 请查看以下从this question借用的代码。

转换器:

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>

见到你!