Đây là mã của tôi:Java XML: ClassCastException DeferredTextImpl
// get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// parse using builder to get DOM representation of the XML file
dom = db.parse(file);
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (SAXException se) {
se.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
NodeList n1 = dom.getChildNodes();
Element e1 = (Element) n1.item(0);
System.out.println(n1.getLength());
System.out.println(e1.getNodeName());
NodeList n2 = n1.item(0).getChildNodes();
Element e2 = (Element) n2.item(0); //Line 61
System.out.println(n2.getLength());
System.out.println(e2.getNodeName());
Đây là tập tin XML của tôi:
<?xml version="1.0" encoding="utf-8"?>
<test-fw:test
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:test-fw="http://simitar/test-fw">
<rule-tree>
<rule class="matchlines">
<property name="contiguous"> true</property>
<property name="inOrder">false</property>
<property name="exact">false</property>
<property name="lines">modelInstantiated</property>
</rule>
<rule class="matchlines">
<property name="contiguous"> true</property>
<property name="inOrder">true</property>
<property name="exact">false</property>
<property name="lines">InitEvent</property>
</rule>
</rule-tree>
</test-fw:test>
Dưới đây là kết quả của tôi:
1
test-fw:test
Exception in thread "main" java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeferredTextImpl cannot be cast to org.w3c.dom.Element
at testpack.Main.run(Main.java:61)
at testpack.Main.main(Main.java:86)
tôi tiếp tục nhận được lỗi này . Tôi hoàn toàn lạc mất. Tôi không có ý tưởng gì để làm. Tôi muốn có thể có một nút, và có thể lấy tất cả các con của nó và đặt chúng vào một mảng hoặc danh sách, vì vậy tôi có thể lặp qua chúng.
Dưới đây là tất cả các hàng nhập khẩu của tôi:
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Stack;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
Tôi đã có thời gian khó khăn nhất cố gắng để có được Java này để phân tích tập tin XML này.
vui lòng đăng nhập của bạn, nghĩ rằng bạn đã bỏ lỡ điều gì đó ở đó. – Frank
Dòng nào là dòng 61? –
Sẽ hữu ích nếu bạn chỉ ra dòng nào trong đoạn mã của bạn là dòng 61. – cjstehno