首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java -读取xml文件

问Java -读取xml文件
EN

Stack Overflow用户
提问于 2014-06-05 17:40:02
回答 1查看 744关注 0票数 1

在Java中,我使用DocumentBuilderFactory、DocumentBuilder和Document来读取xml文件。但是现在我想要创建一个方法,它返回一个数组,其中包含一个给定的节点序列中的所有值。为了更好地解释,我将给出一个示例:假设我有以下xml文件:

代码语言:javascript
复制
<one>
  <two>
    <three>5</three>
    <four>6</four>
  </two>
  <two>
    <three>7</three>
    <four>8</four>
  </two>
</one>

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

我怎样才能建立这个列表呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-06-05 17:57:03

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

代码语言:javascript
复制
    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
    }

您可以找到关于如何使用xpath 这里查询节点的更多信息。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24066690

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档