【问题标题】:Concatenate multiple tags from a .xml file using JAVA使用 JAVA 连接来自 .xml 文件的多个标签
【发布时间】:2018-11-06 06:23:52
【问题描述】:

我想使用 JAVA 连接来自 xml 文件的多个标记值。 .xml 看起来像这样:

<test>
    <testcase>
        <teststep> row 1 </teststep>
        <teststep> row 2 </teststep>
        <teststep> row 3 </teststep>
        <title> Frist Test </title>
    </testcase>
</test>
<test>
    <testcase>
        <teststep> row 20 </teststep>
        <teststep> row 10 </teststep>
        <teststep> row 30 </teststep>
        <title> Second Test </title>
    </testcase>
</test>

结果应该是这样的:

row 1 row 2 row 3
row 10 row 20 row 30

应该有2个变量。

我试过了:

NodeList nodeList5 = doc.getElementsByTagName("teststep");
for (int x = 0, size = nodeList5.getLength(); x < size; x++) {
    description = description + nodeList5.item(x).getTextContent();
}
System.out.println("Test Description: " + description);

但我得到的只是:第 1 行 第 2 行 第 3 行 第 10 行 第 20 行 第 30 行,只有一个变量。

【问题讨论】:

  • 您尝试的代码是 JavaScript。要在 Java 中处理 XML,不要重新发明轮子 - 查找 JAXB 和 JAXP。

标签: java xml concatenation


【解决方案1】:

SimpleXml 可以做到:

final String data = ...
final SimpleXml simple = new SimpleXml();
final CheckedIterator<Element> it = simple.iterateDom(new ByteArrayInputStream(data.getBytes(UTF_8)));
while (it.hasNext()) {
    System.out.println(String.join(" ", selectTestStep(it.next().children.get(0).children)));
}

private static List<String> selectTestStep(final List<Element> elements) {
    final List<String> list = new ArrayList<>();
    for (final Element e : elements)
        if (e.name.equals("teststep"))
            list.add(e.text);
    return list;
}

将输出:

row 1 row 2 row 3
row 20 row 10 row 30

来自 Maven 中心:

<dependency>
    <groupId>com.github.codemonstur</groupId>
    <artifactId>simplexml</artifactId>
    <version>1.4.0</version>
</dependency>

【讨论】:

    【解决方案2】:

    您可以通过首先选择testcase 节点然后选择其中所有子teststep 节点来提取所需的数据

    NodeList testcases = doc.getElementsByTagName("testcase");
    for(int i = 0; i < testcases.getLength(); ++i) {
      Node testcase = testcases.item(i);
      NodeList teststeps = testcase.getChildNodes();
      for (int j = 0; j < teststeps.getLength(); ++j) {
        if(teststeps.item(j).getNodeName().equals("teststep"))
          System.out.print(teststeps.item(j).getTextContent());
      }
      System.out.println();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-22
      • 1970-01-01
      相关资源
      最近更新 更多