Getting attribute value from node using dom4j

My XML is structured as shown below. I am trying to get attribute values ​​from XML using dom4j.

<baz> <foo> <bar a="1" b="2" c="3" /> <bar a="4" b="5" c="6" /> </foo> </baz> 

Currently, nodes are stored in a list with the following code:

 public List<Foo> getFoo() { String FOO_XPATH = "//baz/foo/*"; List<Foo> fooList = new ArrayList<Foo>(); List<Node> fooNodes = _bazFile.selectNodes(FOO_XPATH); for (Node n : fooNodes) { String a = /* get attribute a */ String b = /* get attribute b */ String c = /* get attribute c */ fooNodes.add(new Foo(a, b, c)); } return fooNodes; } 

There is a similar but different question here , but it returns the node value for a known key / attribute value pair using the following code:

 Node value = elem.selectSingleNode("val[@a='1']/text()"); 

In my case, the code knows the keys, but does not know the values ​​- what do I need to store. (The above snippet from a similar question / answer also returns the text value of the node when I need the attribute value.)

+6
source share
3 answers

You need to give Node to Element and then use attribute or attributeValue methods:

 for (Node node : fooNodes) { Element element = (Element) node; String a = element.attributeValue("a"); ... } 

In principle, getting the attribute value from "any node" does not make sense, since some types of node (attributes, text nodes) do not have attributes.

+15
source
 public List<Foo> getFoo() { String FOO_XPATH = "//baz/foo/*"; List<Foo> fooList = new ArrayList<Foo>(); List<Node> fooNodes = _bazFile.selectNodes(FOO_XPATH); for (Node n : fooNodes) { Element element = (Element) n; String a = element.attributeValue("a"); String b = element.attributeValue("b"); String c = element.attributeValue("c"); fooNodes.add(new Foo(a, b, c)); } return fooNodes; } 

I think you need to convert the node to an element, then only its work is beautiful.

+1
source

You can also use xpath to get the value of the node attribute -

  for (Node n : fooNodes) { String a = n.valueOf("@a"); String b = n.valueOf("@b"); String c = n.valueOf("@c"); fooNodes.add(new Foo(a, b, c)); } 
0
source

Source: https://habr.com/ru/post/925225/


All Articles