如何知道XML元素是否以Java编程方式包含数组?

时间:2018-11-27 13:28:23

标签: xml xpath soap xml-parsing complextype

我有一个XML响应:

<abc:parent>
    <abc:item>
        ...
    </abc:item>
    <abc:item>
        ...
    </abc:item>
</abc:parent>

也可能只有一个子元素:

<abc:parent>
    <abc:item>
        ...
    </abc:item>
</abc:parent>

以前,父级具有“ SOAP-ENC:arrayType”属性,可以轻松确定其包含子元素数组,但现在的响应采用先前描述的格式。

以前的示例:

<abc:parent xsi:type="SOAP-ENC:Array" SOAP-ENC:arrayType="Struct[1]" SOAP-ENC:offset="[0]">
    <abc:item>
        ...
    </abc:item> 
</abc:parent>

先前检查的示例:

private void parseNode(DomNode node, String xpath) {
    boolean isLeaf = true;

    for (DomNode childNode : node.getChildren()) {
        if (DomNode.TEXT_NODE != childNode.getNodeType()) {
            isLeaf = false;
        }
    }

    if (!isLeaf) {
        if (node instanceof DomElement) {
            DomElement eNode = (DomElement)node;
            String arrayType = eNode.getAttribute("SOAP-ENC:arrayType");
            if (!PkUtil.isEmpty(arrayType)) {
                // we have a node with an array of children
            }
        }
    }
}

我无法控制回复消息。

如何确定父元素包含子元素数组?在我看来,获得这种结果和信息甚至是不可能的。

1 个答案:

答案 0 :(得分:0)

您可能可以通过检查您拥有的item的数目来完成此操作,如果它有多个item,您就知道它是一个数组:

DomElement eNode = (DomElement) node;
NodeList childList = eNode.getElementsByTagName("item");
if (childList.getLength() > 1) {
    // we have a node with an array of children
}