XML:
<nativeInformation>
<detail id="natural:fieldFormat">A</detail>
</nativeInformation>
我想获得“id”值。但不断收到此错误:org.apache.xerces.dom.DeferredTextImpl无法强制转换为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(“父节点是”+ n.getParentNode());在for循环中会给我,[detail:null]
任何帮助都将非常感激。
答案 0 :(得分:12)
在向下转换为Element之前,请检查
提示: - 只需要检查Nodeis是否为Element。以下是将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);
..............................................
}
]
答案 1 :(得分:0)
查看此代码:
Node n = nodeList.item(i);
final NamedNodeMap attrs = n.getAttributes();
if(attrs !=null){
Node id = attrs.getNamedItem("id");
if(id !=null){
System.out.println("id: "+id.getNodeValue());
}
}