繁体   English   中英

如何在Java中使用XPath获取属性值?

[英]How to get attribute value using XPath in Java?

我使用XPath解析下面的XML:

<?xml version="1.0" encoding="UTF-8"?>
<schema>
  <element name="name_ele1" id="name_id_1" >test name1</element>
  <element name="name_ele2" id="name_id_2" >test name2</element>
  <element name="name_ele2" id="name_id_3" >test name3</element>
</schema>

我想根据我传递的ID从xml文档中获取“名称”,但是我无法获得所需的数据,而是查询返回空白。

XPathExpression expr = xpath.compile("/schema/element[@id='name_id_2']/name/text()");

像这样:

XPathExpression expr = xpath.compile("/schema/element[@id='name_id_2']/@name");

表达式尝试选择name元素中的文本,而不是name属性的值。

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

public class XMLXpathReadder {

    public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException {



         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse(new FileInputStream(new File("C:\\Test.xml")));// same xml comments as above.

            XPathFactory xpf = XPathFactory.newInstance();
            XPath xpath = xpf.newXPath();
            Element userElement = (Element) xpath.evaluate("/schema/element", document,
                XPathConstants.NODE);
            System.out.println(userElement.getAttribute("id"));
            System.out.println(userElement.getAttribute("name"));

    }

}

以上代码为我工作。

但是如何读取所有元素的值。 我只获得第一个元素节点。

<?xml version="1.0" encoding="UTF-8"?>
<schema>
  <element name="name_ele1" id="_1" >test name1</element>
  <element name="name_ele2" id="_2" >test name2</element>
  <element name="name_ele2" id="_3" >test name3</element>
</schema>

暂无
暂无

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

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