do5
do5

Reputation: 73

How to read all the values of an atrribute under an XML tag [dom4j]?

I am using dom4j library(SAXReader) in java and want to know how can I read and fetch all the values of an XML attribute present in the child XML tags of some parent XML tags. for eg.

....
<ParentTag1>
 <ChildTag1 SomeAttributeName1 = "val1">....</ChildTag1>
 <ChildTag2>...</ChildTag2>
 <ChildTag3 SomeAttributeName1 = "val2">...</ChildTag3>
</ParentTag1>
....
<ParentTag2>
 <ChildTag1 SomeAttributeName2 = "val1">....</ChildTag1>
 <ChildTag2>...</ChildTag2>
 <ChildTag3 SomeAttributeName2 = "val2">...</ChildTag3>
</ParentTag2>
......

Let's say the attribute is SomeAttributeName1 Questions:

Thanks

Upvotes: 0

Views: 246

Answers (1)

forty-two
forty-two

Reputation: 12817

Since DOM4J has built-in XPATH support, using that is probably the best apprach:

    List<String> values = doc.selectNodes("//ParentTag1//@SomeAttributeName1")
            .stream()
            .map(node -> node.getText())
            .collect(Collectors.toList());

The XPATH expression selects all Attribute nodes in all elements that have an ancestor element named ParentTag1.

Upvotes: 0

Related Questions