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

发布于 2025-01-09 02:10:34 字数 506 浏览 0 评论 0原文

我有一个如下的 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>

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

一种方法是我可以通过使用 Document 接口解析此 xml 来准备姓名到年龄的映射。

但是有没有任何API可以让我调用Document接口,在其中我可以说获取名称为say,ghi的元素,然后我可以迭代所有属性以获取年龄属性或任何其他简单的方法来获取名称值为的年龄,说吉?

I have an xml as follow:

<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>

I want to fetch the value of age tag for a given value of name tag?

One way is that I can prepare a map of name to age by parsing this xml using Document interface.

But is there any api that I can just call for Document interface in which I can say fetch element where name is say,ghi, and then i can iterate all atributes to get age attribute or any other simple way to get age where name value is,say ghi?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

赴月观长安 2025-01-16 02:10:34

结果java确实在XPath评估器中提供docs.oracle.com/en/java/javase/17/docs/api/java.xml/javax/xml/xpath/package-summary.html" rel="nofollow noreferrer">javax.xml.xpath 包,这使得这变得很简单:

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

Turns out java does come with an XPath evaluator in the javax.xml.xpath package, which makes this trivial:

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");       
    }
}

Example use:

$ java Demo.java
ghi is 40 years old
绝不服输 2025-01-16 02:10:34

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

/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);

XPath is a very expressive API that can be used to select the elements.

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

This article https://www.baeldung.com/java-xpath provides a pretty good overview and explanation of how to apply an XPath in Java.

Adjusting one of their code samples for your 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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文