【发布时间】:2015-10-02 13:54:29
【问题描述】:
我正在使用带有 java 的 DOM 解析器来解析 XML 字符串。为了调试,我使用了这种递归方法:
public static void visitRecursively(Node node) {
// get all child nodes
count ++;
System.out.println("count == " + count);
NodeList list = node.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
// get child node
Node childNode = list.item(i);
//you need to get the attributes
NamedNodeMap attributeList = childNode.getAttributes();
for (int j = 0; j < attributeList.getLength(); j++) {
System.out.println("Attribute: "
+ attributeList.item(j).getNodeName() + " = "
+ attributeList.item(j).getNodeValue());
System.out.println("Node: " + childNode.getNodeName()
+ " - with value: " + childNode.getNodeValue());
}
visitRecursively(childNode);
}
对应的XML是这样的:
<ObligationExpression
ObligationId="urn:oasis:names:tc:xacml:example:obligation:emailPermit"
FulfillOn="Permit">
<AttributeAssignmentExpression
AttributeId="urn:oasis:names:tc:xacml:3.0:example:attribute:text">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">
Your resource below has been
accessed by:
</AttributeValue>
</AttributeAssignmentExpression>
</ObligationExpression>
我在递归调用 #2 时遇到空指针异常。
输出:
urn:oasis:names:tc:xacml:example:obligation:emailPermit
count == 1
Attribute: FulfillOn = Permit
Node: ObligationExpression - with value: null
Attribute: ObligationId = urn:oasis:names:tc:xacml:example:obligation:emailPermit
Node: ObligationExpression - with value: null
count == 2
我不知道究竟是为什么。
【问题讨论】:
-
你希望得到什么样的输出?
-
我编辑了问题以提高准确性