XML:
<nativeInformation>
<detail id="natural:fieldFormat">A</detail>
</nativeInformation>
我正在尝试获取“id”值。但不断收到此错误:org.apache.xerces.dom.DeferredTextImpl cannot be cast to org.w3c.dom.Element
我的代码:
for (int i = 0; i < nodeList.getLength(); i++) {
String s;
Node n = nodeList.item(i);
Attr attrName = ((Element) n).getAttributeNode("id");
if (attrName.getValue()!=null) {
s = attrName.getValue();
System.out.println(s);
}
}
如果我写:System.out.println("parent node is "+n.getParentNode());在给我的 for 循环中,[detail: null]
任何帮助将不胜感激。
最佳答案
在将节点转换为元素之前,您需要检查节点是否为元素。这是将 Node 转换为 Element 的方法:
NodeList nodes = root.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
if (nodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) nodes.item(i);
}
}
关于java - 错误 : org. apache.xerces.dom.DeferredTextImpl 无法转换为 org.w3c.dom.Element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21170909/