java xml将节点转换为元素

java xml将节点转换为元素,java,xml,xml-parsing,Java,Xml,Xml Parsing,我知道这个问题被问了很多次,但我仍然无法让它发挥作用。我将xml字符串转换为文档对象,然后解析它。代码如下: import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.*; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBu

我知道这个问题被问了很多次,但我仍然无法让它发挥作用。我将xml字符串转换为文档对象,然后解析它。代码如下:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try
{
  builder = factory.newDocumentBuilder();  
  Document document = builder.parse( new InputSource( new StringReader( result ) ) );
  Node head = document.getFirstChild();
  if(head != null)
  {                  
    NodeList airportList = head.getChildNodes();      
    for(int i=0; i<airportList.getLength(); i++) {
    Node n = airportList.item(i);                        
    Element airportElem = (Element)n;
  }
}
catch (Exception e) {
  e.printStackTrace();
} 
import javax.xml.parsers.DocumentBuilder;
导入javax.xml.parsers.DocumentBuilderFactory;
导入org.w3c.dom.*;
DocumentBuilderFactory工厂=DocumentBuilderFactory.newInstance();
文档生成器;
尝试
{
builder=factory.newDocumentBuilder();
documentdocument=builder.parse(新的InputSource(新的StringReader(结果));
节点头=document.getFirstChild();
if(head!=null)
{                  
NodeList airportList=head.getChildNodes();
对于(int i=0;i
当我将节点对象n转换为元素时,我得到一个异常java.lang.ClassCastException:org.apache.harmony.xml.dom.TextImpl不能转换为org.w3c.dom.Element。当我检查节点对象的节点类型时,它会显示Node.TEXT\u Node。我相信它应该是Node.Element\u Node。我说的对吗

可能不是,解析器可能是对的。这意味着您正在解析的部分节点是。例如:

<foo>bar</foo>
如果您的XML文档字面上看像上面所示,那么它包含一个根元素
foo
,其中包含以下子节点(按顺序):

  • 包含一些空格的文本节点
  • 一个
    元素
  • 包含更多空白的文本节点
请注意,
bar
元素不是
foo
的第一个子元素

<foo><bar>baz</bar></foo>
baz

那么
bar
元素将是
foo

的第一个子元素,我想您需要这样的东西:

NodeList airportList = head.getChildNodes();
for (int i = 0; i < airportList.getLength(); i++) {
    Node n = airportList.item(i);
    if (n.getNodeType() == Node.ELEMENT_NODE) {
        Element elem = (Element) n;
    }
}
NodeList airportList=head.getChildNodes();
对于(int i=0;i
您也可以尝试“保护”您的角色

Node n = airportList.item(i);
if (n instanceof Element)
{                        
    Element airportElem = (Element)n;
    // ...
}

但正如其他人所指出的,您有文本节点,这些节点不会通过此方法铸造,请确保您不需要使用条件来使用不同的代码来处理它们

当您没有向我们显示文档时,我们如何知道第一个节点应该是元素还是文本?我强烈怀疑解析器是正确的……我我怀疑您可能只是想跳过非元素节点。我添加了xml。节点应该是元素,而不是文本。我说的对吗?是的,但我想您会发现在
之间以及在每个
之间有一个文本元素(可能只是换行符)。元素的包命名空间是什么?
NodeList airportList = head.getChildNodes();
for (int i = 0; i < airportList.getLength(); i++) {
    Node n = airportList.item(i);
    if (n.getNodeType() == Node.ELEMENT_NODE) {
        Element elem = (Element) n;
    }
}
Node n = airportList.item(i);
if (n instanceof Element)
{                        
    Element airportElem = (Element)n;
    // ...
}