10

My XML is structured like the example below. I'm trying to get the attribute values out of XML using dom4j.

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

Currently the nodes are stored into 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 on SO but that is returning a node's value for a known attribute key/value pair using the following code:

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

In my case, the code knows the keys but doesn't know the values - that's what I need to store. (The above snippet from the similar question/answer also returns a node's text value when I need the attribute value.)

Community
  • 1
  • 1
anjunatl
  • 1,027
  • 2
  • 11
  • 24

3 Answers3

23

You have to cast the Node to Element and then use the attribute or attributeValue methods:

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

Basically, getting the attribute value from "any node" doesn't make sense, as some node types (attributes, text nodes) don't have attributes.

Abdull
  • 26,371
  • 26
  • 130
  • 172
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4

You can also use xpath to get the value of a 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));
  }
Jay Shark
  • 635
  • 1
  • 11
  • 21
1
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 node into element then only its works fine.

Ami
  • 4,241
  • 6
  • 41
  • 75