Iterator does not return the Element Object or does not Cast to its corresponding object?
Could someone please tell me why the Iterator in this code does not return with he Element Object?!? Can't cast to Element Object! This is a JDOM implementation of SAX!
org.xml.sax.InputSource inStream = new org.xml.sax.InputSource();
inStream.setCharacterStream(new java.io.StringReader(开发者_Go百科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();
}
Consider this XML document:
<root>
<child/>
</root>
The descendants of the root are:
- a text node containing the newline char + 4 spaces
- the child element
- a text node containing the newline char
Also, getDescendants
walks through all the descendants, and not just the immediate children of the element. I'm pretty sure that it's not what you want.
You need to pass an ElementFilter
to getDescentdents(Filter filter)
XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
<child1>
<child11></child11>
<child12></child12>
</child1>
<child2></child2>
</root>
Example
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);
}
Output
[Element: <child1/>]
[Element: <child11/>]
[Element: <child12/>]
[Element: <child2/>]
精彩评论