正在解析 java 中的 Xml 文件以获取与给定标签值匹配的元素

Parsing Xml file in java to fetch the element matching given tag value

我有一个 xml 如下:

<root>

<outer>
<name>abc</name>
<age>20</age>
</outer>

<outer>
<name>def</name>
<age>30</age>
</outer>

<outer>
<name>ghi</name>
<age>40</age>
</outer>


</root>

我想获取给定名称标签值的年龄标签值?

一种方法是,我可以通过使用文档界面解析这个 xml 来准备一个名字到年龄的映射。

但是有没有任何 api 我可以调用 Document 接口,在其中我可以说 fetch element where name is say,ghi,然后我可以迭代所有属性以获得年龄属性或任何其他获取名称值所在年龄的简单方法,比如 ghi?

XPath 是一个非常有表现力的API,可用于select 元素。

/root/outer[name = "ghi"]/age

这篇文章 https://www.baeldung.com/java-xpath 很好地概述了如何在 Java 中应用 XPath。

正在为您的 XPath 调整他们的代码示例之一:

String name = "ghe";

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(this.getFile());
XPath xPath = XPathFactory.newInstance().newXPath();

String expression = "/root/outer[name=" + "'" + name + "'" + "]/age";
node = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);

原来 java 确实带有 XPath evaluator in the javax.xml.xpath package,这使得这变得微不足道:

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;

public class Demo {
    public static void main(String[] args) throws Exception {
        String name = "ghi";
        // XPath expression to find an outer tag with a given name tag
        // and return its age tag
        String expression = String.format("/root/outer[name='%s']/age", name);
        
        // Parse an XML document
        DocumentBuilder builder
            = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = builder.parse(new File("example.xml"));

        // Get an XPath object and evaluate the expression
        XPath xpath = XPathFactory.newInstance().newXPath();
        int age = xpath.evaluateExpression(expression, document, Integer.class);

        System.out.println(name + " is " + age + " years old");       
    }
}

使用示例:

$ java Demo.java
ghi is 40 years old