有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我正在尝试使用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(事件对象),这样我就可以添加到存储xml中

谢谢


共 (1) 个答案

  1. # 1 楼答案

    要做到这一点,我必须把所有的东西都稀释成基本的字符串。我创建了一个将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();