java xml cast Node to Element
2022-09-04 06:15:57
我知道这个问题被问过很多次,但我仍然无法让它工作。我将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();
}
当我将 Node 对象 n 转换为 Element 时,我得到一个异常 java.lang.ClassCastException:org.apache.harmony.xml.dom.TextImpl 不能被强制转换为 org.w3c.dom.Element。当我检查 Node 对象的节点类型时,它显示Node.TEXT_NODE。我认为应该Node.ELEMENT_NODE。我说的对吗?
那么我如何将Node转换为Element,这样我就可以做一些类似element.getAttribute(“attrName”)的事情。
这是我的XML:
<?xml version="1.0" encoding="utf-8" ?>
<ArrayOfCity xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
<City>
<strName>Abu Dhabi</strName>
<strCode>AUH</strCode>
</City>
<City>
<strName>Amsterdam</strName>
<strCode>AMS</strCode>
</City>
<City>
<strName>Antalya</strName>
<strCode>AYT</strCode>
</City>
<City>
<strName>Bangkok</strName>
<strCode>BKK</strCode>
</City>
</ArrayOfCity>
提前致谢!