有人可以告诉我为什么此代码中的迭代器不会返回Element对象吗?!?无法转换为Element Object!这是SAX的JDOM实现!
org.xml.sax.InputSource inStream = new org.xml.sax.InputSource();
inStream.setCharacterStream(new java.io.StringReader(temp));
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(inStream);
ArrayList<String> queries = new ArrayList<String>();
Element root = doc.getRootElement();
Iterator elemIter = root.getDescendants();
while (elemIter.hasNext()) {
**Element tempElem = (Element)elemIter.next();**
String CDATA = tempElem.getChildText("ZQuery");
queries.add(CDATA);
elemIter.next();
}
答案 0 :(得分:1)
考虑这个XML文档:
<root>
<child/>
</root>
根的后代是:
此外,getDescendants
遍历所有后代,而不仅仅是元素的直接子元素。我很确定这不是你想要的。
答案 1 :(得分:0)
您需要将ElementFilter
传递给getDescentdents(Filter filter)
XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
<child1>
<child11></child11>
<child12></child12>
</child1>
<child2></child2>
</root>
实施例
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new File("src/com/foo/test.xml"));
Element root = document.getRootElement();
ElementFilter filter = new ElementFilter();
Iterator i = root.getDescendants(filter);
while (i.hasNext()) {
Element element = (Element) i.next();
System.out.println(element);
}
输出
[Element: <child1/>]
[Element: <child11/>]
[Element: <child12/>]
[Element: <child2/>]