使用Xstream构造此xml的正确方法

时间:2014-06-27 10:10:50

标签: java xml xstream

我正在尝试使用XStream实现以下功能:

<?xml version="1.0" encoding="UTF-8"?>
<rows>
    <row id="EventID">
        <cell>false</cell>
        <cell>Mainland</cell>
        <cell></cell>
        <cell></cell>

        <row id = "StoreID">
            <cell></cell>
            <cell></cell>
            <cell></cell>
            <cell></cell>
        </row>

    </row>
</rows>

在这里我们可以看到id为“StoreID”的行实际上是“EventID”行的子行。我可以通过以下方式单独创建:

    String xml = "", eventXML = "", storeXml = "";
    StringBuffer buff = new StringBuffer(1000);
    buff.append("<?xml version='1.0' encoding='iso-8859-1'?>");

    XStream xstream = new XStream(new DomDriver());


    xstream.alias("rows", List.class);
    xstream.alias("row", Event.class);

    xstream.registerConverter(evtConverter);

    for( Event e: events )
    {
        // Get a list of stores
        Store store = e.getStore();
        xstream.registerConverter( storeConverter, XStream.PRIORITY_VERY_HIGH );

        xstream.alias("row", Store.class);
        storeXml = xstream.toXML( store );

        xml = xstream.toXML(e);
    }
    return xml;

那我怎么去组合呢?有没有办法停止自动关闭xml(Event对象),以便我可以添加Store xml?

由于

1 个答案:

答案 0 :(得分:0)

要做到这一点,我必须把所有东西都稀释到基本字符串。我创建了一个将xml字符串组合在一起的方法:

private static String combineStrings(String eventXML, String storeXML) {
    String newXML = "";

    Pattern pattern = Pattern.compile("</row>");
    Matcher matcher = pattern.matcher(eventXML);

    int posForStoreXML = 0;

    boolean found = false;
    while (matcher.find()) {
        posForStoreXML = matcher.start() - 1;
        found = true;
    }
    if (!found) {
        System.err.println("No match found");
    }

    StringBuilder builder = new StringBuilder(eventXML);
    builder.insert(posForStoreXML, storeXML);

    System.out.println(builder.toString());
    newXML = builder.toString();

    return newXML;
}

这必须在这里调用:

for (Event_BACKUP e : events) {
        // Get a list of stores
        Store store = e.getStore();
        xstream.registerConverter(storeConverter,
                XStream.PRIORITY_VERY_HIGH);
        xstream.alias("row", Store.class);

        storeXml = xstream.toXML(store);
        xml = xstream.toXML(e);
        **xml = combineStrings(xml, storeXml);**

        buffer.append(xml);
    }
    buffer.append( "</rows>" );
    xml = buffer.toString();