How to retrieve specific element (or nodelist) within an existing element from DOM in Java
I am trying to parse an XML file which contains multiple records of name A
. Each A
has multiple group records with name B
. The various records within B
have names x
, y
an开发者_如何转开发d z
.
My questions are:
- How do I navigate to
B
and - how do I obtain all values of
x
in loop.
The DOM is set to the document (i.e. elements of name "A")
I am using a DOM parser in Java.
Sample record:
<A>
<B><x>123</x><y>asdf</y><z>A345</z></B>
<B><x>987</x><y>ytre</y><z>Z959</z></B>
</A>
Document yourDom = ....;
XPathFactory xpf = XPathFactory.newInstance();
XPath xp = xpf.newXPath();
XPathExpression xpe = xp.compile("//A/B/*");
NodeList nodes = (NodeList) xpe.evaluate(yourDom, XPathConstants.NODESET);
Apart from using the standard DOM API directly which is usually a bit verbose for these tasks, you could also use jOOX as a jquery-like wrapper for DOM. Here's an example how to use it:
// Loop over all x element values within B using css-style selectors
for (String x : $(document).find("B x").texts()) {
// ...
}
// Loop over all x element values within B using XPath
for (String x : $(document).xpath("//B/x").texts()) {
// ...
}
// Loop over all x element values within B using the jOOX API
for (String x : $(document).find("B").children("x").texts()) {
// ...
}
精彩评论