如何知道 XML 元素是否以编程方式包含 Java 中的数组?
How to know if XML element contains an array programmatically in Java?
我有一个 XML 回复:
<abc:parent>
<abc:item>
...
</abc:item>
<abc:item>
...
</abc:item>
</abc:parent>
也可能只有一个子元素:
<abc:parent>
<abc:item>
...
</abc:item>
</abc:parent>
以前 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
}
}
}
}
我无法控制响应消息。
如何确定父元素包含子元素数组?对我来说,这个结果和信息似乎是不可能的。
你可以通过检查你拥有的 item
的数量来做到这一点,如果它有多个 item
你就知道它是一个数组:
DomElement eNode = (DomElement) node;
NodeList childList = eNode.getElementsByTagName("item");
if (childList.getLength() > 1) {
// we have a node with an array of children
}
我有一个 XML 回复:
<abc:parent>
<abc:item>
...
</abc:item>
<abc:item>
...
</abc:item>
</abc:parent>
也可能只有一个子元素:
<abc:parent>
<abc:item>
...
</abc:item>
</abc:parent>
以前 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
}
}
}
}
我无法控制响应消息。
如何确定父元素包含子元素数组?对我来说,这个结果和信息似乎是不可能的。
你可以通过检查你拥有的 item
的数量来做到这一点,如果它有多个 item
你就知道它是一个数组:
DomElement eNode = (DomElement) node;
NodeList childList = eNode.getElementsByTagName("item");
if (childList.getLength() > 1) {
// we have a node with an array of children
}