简体   繁体   English

如何在Java中使用XPath查询选择元素的属性值并将其放入字符串中?

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

I am pretty new in XPath query into Java and I have the following problem: 我是XPath查询Java的新手,但存在以下问题:

I have a org.jdom.Document documentXML variable that contains the following XML content: 我有一个org.jdom.Document documentXML变量,其中包含以下XML内容:

<?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) 我必须选择id属性中的值并将其放入字符串中(因此我必须将“ MyID”值放入字符串中)

In Java I have to something like this (that don't work): 在Java中,我必须执行以下操作(不起作用):

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 因此,您可以看到documentXML变量包含先前的XML代码

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) 我创建一个XPath查询来访问驱动器节点的id属性的值,然后尝试将此值放入driveId (这是一个String对象)

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 TNX

Andrea 安德里亚

Like you already mentioned, the id you want to get is an attribute . 就像您已经提到的,您要获取的ID是一个attribute

Hence, you just have to change your cast from org.jdom.Element to org.jdom.Attribute . 因此,你只需要改变你的施法距离org.jdom.Elementorg.jdom.Attribute Then you can call driveId.getValue() to get the String value for id. 然后,您可以调用driveId.getValue()以获取id的String值。

您可以使用jcabi-xml并在一行中完成此操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM