我已经失去了两个小时试图解析XML,我很恐慌。希望你们能帮助我。
我有一个像这样的XML文件:
<document src="xmls/sections/master/37_11.xml">
<name>Somename</name>
<list show="grid">
<filter>
<option id="1">A</option>
<option id="2">B</option>
<option id="3">C</option>
<option id="4">D</option>
<option id="5">E</option>
<option id="6">F</option>
</filter>
<item id="3" detail="true">
<filter>
<value id="1">A</value>
</filter>
<logo src="media/img/" alt=""></logo>
<name>this is a name</name>
<description>content</description>
<icons></icons>
</item>
<item id="3" detail="true">
<filter>
<value id="1">A</value>
</filter>
<logo src="media/img/" alt=""></logo>
<name>this is a name</name>
<description>content</description>
<icons></icons>
</item>
</list>
</document>
所以我在Java中使用这个解析器:
this.contingut = new File("file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(contingut);
doc.getDocumentElement().normalize();
NodeList nodes = doc.getElementsByTagName("list");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
Element element = (Element) node;
if(element.getNodeType() == Element.ELEMENT_NODE){
//section.setProductType(getValueInt("product_type", element));
NodeList child = element.getChildNodes();
//fem el parsing de la galeria d'elements de list:
Log.d("debugging","Tipus de mostrar?"+element.getAttribute("show")); //THIS IS WORKING
NodeList filtersTags = element.getElementsByTagName("filter");
Node listNode = filtersTags.item(0);
Element listElement = (Element) listNode;
if(listElement.getNodeType() == Element.ELEMENT_NODE){
NodeList fillsList = listElement.getChildNodes(){
Log.d("debugging","QttFills listElement: "+fillsList.getLength());
for (int k=0; k<fillsList.getLength();k++){//donem voltes als fills de list.
Node fillList = fillsList.item(k);
Element elementList = (Element) fillList;
if(elementList.getNodeType() == Element.ELEMENT_NODE){
if (elementList.getNodeName().equals("filter")){
Log.d("debugging","Filter!!!");
} else if (elementList.getNodeName().equals("i")){
Log.d("debugging","item!!!");
}
}
}
}
}
我得到了
java.lang.ClassCastException:org.apache.harmony.xml.dom.TextImpl无法强制转换为org.w3c.dom.Element 上:
Element elementList = (Element) fillList;
你能帮助我吗?我不明白为什么会崩溃...
非常感谢你。
答案 0 :(得分:2)
这就是我让你的代码做你想做的事情:
for (int k=0; k<fillsList.getLength();k++){//donem voltes als fills de list.
Node fillList = fillsList.item(k);
if (fillList instanceof Element) {
Element elementList = (Element) fillList;
if(elementList.getNodeType() == Element.ELEMENT_NODE) {
if (elementList.getNodeName().equals("filter")){
System.out.println("Filter!!!");
} else if (elementList.getNodeName().equals("option")){
System.out.println("item!!!");
}
}
}
}
答案 1 :(得分:0)
从我发现的文档中,TextImpl
只实现了Node
接口,而不是Element
接口。所以代码在这里:
Node fillList = fillsList.item(k);
Element elementList = (Element) fillList;
fillList
类型为TextImpl
时,将失败。请注意,这发生在两个if
测试之间的。