繁体   English   中英

JAVA - 读取 XML 节点的属性

[英]JAVA - Read the attributes of an XML node

我正在尝试使用 XPath 库读取 XML 文件的行。 到目前为止,我已经能够读取我正在处理的文档的每个节点,但我不知道如何访问节点的特定属性。

为了更好地理解,我将给出一个示例以及我迄今为止开发的代码:

<string key1="/path" key2="title" key3="English" value="Spanish"/>
<string key1="/path" key2="title" key3="English" value="Spanish"/>
<string key1="/path" key2="title" key3="English" value="Spanish"/>
<string key1="/path" key2="title" key3="English" value="Spanish"/>

我想要做的是获取示例中所有节点都包含文本“Spanish”的 value 属性的值。

使用以下代码我阅读了每一行,但我不知道如何使用 Java XPath 库访问属性的值:

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

        String xPathExpression = "//string";

        Document documento = null;
        NodeList nodos = null;

        try {
            // Carga del documento xml
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            documento = builder.parse(new File("./src/TestResults/xmlFile.lang"));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        try {
            // Preparación de xpath
            XPath xpath = XPathFactory.newInstance().newXPath();

            // Consultas
            nodos = (NodeList) xpath.evaluate(xPathExpression, documento, XPathConstants.NODESET);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        for (int i=0;i<nodos.getLength();i++){
            System.out.println("********* ITER " + i + " *********");
            System.out.println(nodos.item(i).getNodeName());
            System.out.println(nodos.item(i).getNodeValue());
            System.out.println(nodos.item(i).getAttributes());
            System.out.println("**************************");
        }

}

有点不清楚您想要实现什么,但如果您想要 'value' 属性的值,XPath 表达式可能是:

//string/@value

其中“@”是attribute轴的简写。 也可以写成

//string/attribute::value

尝试

nodos.item(i).getAttributes().getNamedItem("value").getNodeValue();

暂无
暂无

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

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