我有以下 xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<c1>
<c2 id="0001" n="CM" urlget="/at/CsM" urle="/E/login.jsp">
</c2>
<c2 id="0002" n="C2M" urlget="/a2t/CsM" urle="/E2/login.jsp">
</c2>
</c1>
我正在尝试以这种方式加载 c2 的属性:
Document d =
DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse("epxy.xml");
Element c1 = d.getDocumentElement();
Element c2 = (Element)c1.getFirstChild();
while (c2 != null) {
...
c2 = (Element)c2.getNextSibling();
}
但我得到异常 java.lang.ClassCastException: org.apache.xerces.dom.DeferredTextImpl incompatible with org.w3c.dom.Element 在行中
Element c2 = (Element)c1.getFirstChild();
在循环之前。
有什么提示吗?谢谢。
最佳答案
第一个 child 是 c1 结尾和 c2 开头之间的空白。
使用 w3c DOM 遍历树并不是那么容易。如果不用w3c,我推荐dom4j - 使用起来更方便。例如,它会过滤元素中的文本节点,因此您可以调用
List children = c1.elements();
或者,按名称限制
List children = c1.elements("c2");
关于java - ClassCastException 读取 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2901332/