How to select and put into a String an attribute value of an element using XPath query in Java?

1.4k views Asked by At

I am pretty new in XPath query into Java and I have the following problem:

I have a org.jdom.Document documentXML variable that contains the following XML content:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <status>
    <id>0</id>
    <message>Operazione conclusa con successo</message>
  </status>
  <drivers>
    <drive id="MyID">
      <propery1 />
      <property2 />
      <property3 />
      <property4>0</property4>
      <sproperty5>104857600</property5>
      <property6 />
    </drive>
  </drivers>
</root>

I have to select the value inside the id attribute and put it into a String (so I have to put the "MyID" value inside a String)

In Java I have to something like this (that don't work):

org.jdom.output.XMLOutputter xmlOutputterCDATAContent = new org.jdom.output.XMLOutputter(org.jdom.output.Format.getPrettyFormat());

xmlOutputter.output(documentXML, System.out);

xPath = XPath.newInstance("/root/drivers/drive/@id");
objectElement = (Element) xPath.selectSingleNode(documentXML);
driveId = objectElement.getValue();
System.out.println("ID " + objectElement.getValue() + " /ID");

So, as you can see the documentXML variable contains the previous XML code

I create an XPath query to access to the value of id attribute of the drive node, then I try to put this value into the driveId (that is a String object)

But in this way can't work and when I run this code I obtain the following error message:

java.lang.ClassCastException: org.jdom.Attribute cannot be cast to org.jdom.Element

What is the problem? What am I missing? How can I solve?

Tnx

Andrea

2

There are 2 answers

0
yegor256 On

You can use jcabi-xml and accomplish this in one line:

String id = new XMLDocument(xml).xpath("/root/drivers/drive/@id").get(0);
0
Simikolon On

Like you already mentioned, the id you want to get is an attribute.

Hence, you just have to change your cast from org.jdom.Element to org.jdom.Attribute. Then you can call driveId.getValue() to get the String value for id.