JDOM.Element.getChild(String) is returning unexpected results
문제
According to the API at jdom.org, the semantics of getChild(String name)
:
This returns the first child element within this element with the given local name and belonging to no namespace. If no elements exist for the specified name and namespace, null is returned.
Therefore, if I have an XML structure like:
<?xml version="1.0" encoding="UTF-8"?>
<lvl1>
<lvl2>
<lvl3/>
</lvl2>
</lvl1>
I have a JDOM Element which is currently pointing to <lvl1>
. I should be able to make the following call:
Element lvl3 = lvl1Element.getChild("lvl3");
and lvl3
should have non-null.
However, I'm finding that lvl3
is actually null
. Am I missing something?
Here is a sample code snippet that should work:
import java.io.StringReader;
import org.jdom.*;
public static void main(String[] args){
Document doc = new SAXBuilder().build(new StringReader("path to file"));
Element lvl1Element = doc.getRootElement();
Element lvl3Element = lvl1Element.getChild("lvl3"); //is null. Why?
}
해결책
In order to get the functionality I was looking for, I used an Iterator
from the getDescendants(ElementFilter)
function from jdom.org
I then got the Element
I was looking for by using code similar to the following:
Element lvl3 = lvl1.getDescendants(new ElementFilter("lvl3"));
다른 팁
You've just said it....
This returns the first child element within this element with the given local name...
Basically, on lvl1
, your first child is lvl2
. I haven't used JDOM to help further. My suggestion is to go to lvl2
and retrieve lvl3
.
---lvl1
---lvl2(child of lvl1)
---lvl3(child of lvl2)