Java - 读取 xml 文件 [英] Java - read xml file

查看:39
本文介绍了Java - 读取 xml 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,我使用 DocumentBuilderFactory、DocumentBuilder 和 Document 来读取 xml 文件.但是现在我想创建一个方法,该方法返回遵循给定节点序列的所有值的数组列表.为了更好地解释,我将举一个例子:假设我有以下 xml 文件:

In Java I am using DocumentBuilderFactory, DocumentBuilder, and Document to read an xml file. But now I want to make a method that returns an arraylist of all values which follow a given node sequence. To explain better I'll give an example: Say I have the following xml file:

<one>
  <two>
    <three>5</three>
    <four>6</four>
  </two>
  <two>
    <three>7</three>
    <four>8</four>
  </two>
</one>

我使用带有字符串参数one.two.three"的方法,现在返回值应该是一个包含数字 5 和 7 的数组.

And I use the method with a string parameter "one.two.three", now the return value should be an array containing the numbers 5 and 7.

如何构建这个数组列表?

How can I build this arraylist?

推荐答案

您可以使用 xpath,尽管语法与点(使用斜杠)略有不同

you can use xpath, albeit the syntax is slightly different than dots (uses slash)

    Document d = ....

    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile("/one/two/three/text()"); // your example expression
    NodeList nl = (NodeList) expr.evaluate(d, XPathConstants.NODESET);
    for (int i = 0; i < nl.getLength(); i++) {
        String n = nl.item(i).getTextContent();
        System.out.println(n); //now do something with the text, like add them to a list or process them directly
    }

您可以在此处

这篇关于Java - 读取 xml 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆