java - 错误 : org. apache.xerces.dom.DeferredTextImpl 无法转换为 org.w3c.dom.Element

标签 java xml dom

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/

相关文章:

java - JUnit 在测试中捕获异常

java - Eclipse 不会创建 JLabels

Javascript .removeChild 未按预期工作

javascript - 允许内容文档(网页)检测我的 Firefox 插件

javascript - jQuery 模板 - 将数据关联到模板 DOM 元素

java - 如何在 android 日历 View 中仅显示当前月份

java - 如何在保持顺序的情况下将 int 转换为 byte

xml - 如何在 Xpath "contains()"函数中使用变量节点集

c# - 如何使用 LINQ 对 XML 数据执行 OrderBy?

c# - 继承类的无效输出