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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21170909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:06:04  来源:igfitidea点击:

Error: org.apache.xerces.dom.DeferredTextImpl cannot be cast to org.w3c.dom.Element

javaxmldom

提问by ron

XML:

XML:

<nativeInformation>
       <detail id="natural:fieldFormat">A</detail>
</nativeInformation>

I am trying to get the "id" value. but keep getting this error: org.apache.xerces.dom.DeferredTextImpl cannot be cast to org.w3c.dom.Element

我正在尝试获取“id”值。但不断收到此错误:org.apache.xerces.dom.DeferredTextImpl cannot be cast to org.w3c.dom.Element

My code:

我的代码:

  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);              
      } 
     } 

If I write : System.out.println("parent node is "+n.getParentNode()); inside the for loop that will give me, [detail: null]

如果我写: System.out.println("parent node is "+n.getParentNode()); 在给我的 for 循环中,[详细信息:空]

Any help will be really appreciated.

任何帮助将不胜感激。

采纳答案by Naren

Before downcasting to Element ,check this

在向下转换到 Element 之前,检查这个

Hint:- Just need to check the Nodeis an Element or not . Following is the way to convert Node into Element.

提示:- 只需要检查 Nodeis an 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);
         ..............................................
    }
]