使用 JAVA 连接.xml文件中的多个标签



我想使用 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,只有一个变量。

可以通过首先选择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();
}

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

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

最新更新