1

这是我的xml:

例子:

<?xml version="1.0" encoding="UTF_8" standalone="yes"?>
<StoreMessage xmlns="http://www.xxx.com/feed">
    <billingDetail>
        <billingDetailId>987</billingDetailId>       
        <contextId>0</contextId>
        <userId>
            <pan>F0F8DJH348DJ</pan>
            <contractSerialNumber>46446</contractSerialNumber>            
        </userId>            
        <declaredVehicleClass>A</declaredVehicleClass>
    </billingDetail>
    <billingDetail>
        <billingDetailId>543</billingDetailId>       
        <contextId>0</contextId>
        <userId>
            <pan>F0F854534534348DJ</pan>
            <contractSerialNumber>4666546446</contractSerialNumber>            
        </userId>            
        <declaredVehicleClass>C</declaredVehicleClass>
    </billingDetail>
</StoreMessage>

使用 JDOM 解析器,我想从中获取所有<billingDetail>xml 节点。

我的代码:

SAXBuilder builder = new SAXBuilder();
try {
    Reader in = new StringReader(xmlAsString);
    Document document = (Document)builder.build(in);
    Element rootNode = document.getRootElement();
    List<?> list = rootNode.getChildren("billingDetail");

    XMLOutputter outp = new XMLOutputter();
        outp.setFormat(Format.getCompactFormat());

        for (int i = 0; i < list.size(); i++) {

            Element node = (Element)list.get(i);

            StringWriter sw = new StringWriter();
            outp.output(node.getContent(), sw);
            StringBuffer sb = sw.getBuffer();

            String text = sb.toString();
            xmlRecords.add(sb.toString());
        }

} catch (IOException io) {
    io.printStackTrace();
} catch (JDOMException jdomex) {
    jdomex.printStackTrace();
}

但我从来没有像字符串一样输出xml节点:

<billingDetail>
    <billingDetailId>987</billingDetailId>       
    <contextId>0</contextId>
    <userId>
        <pan>F0F8DJH348DJ</pan>
        <contractSerialNumber>46446</contractSerialNumber>            
    </userId>            
    <declaredVehicleClass>A</declaredVehicleClass>
</billingDetail>

我做错了什么?如何使用 JDOM 解析器获得此输出?

编辑

以及为什么如果 XML 以

<StoreMessage>而是喜欢<StoreMessage xmlns="http://www.xxx.com/MediationFeed">

然后工作?这怎么可能?

4

1 回答 1

4

问题是 getChildren 方法有两个版本:

java.util.List getChildren(java.lang.String name) 这将返回直接嵌套在此元素内(一层深)的所有子元素的列表,具有给定的本地名称并且不属于任何命名空间,作为 Element 对象返回。

java.util.List getChildren(java.lang.String name, Namespace ns) This returns a List of all the child elements nested directly (one level deep) within this element with the given local name and belonging to the given Namespace, returned as Element objects.

The first one doesn't find your node if it belongs to a namespace, you should use the second one.

于 2012-09-25T11:50:40.200 回答