gpt4 book ai didi

java - java中遍历XML节点的问题

转载 作者:行者123 更新时间:2023-12-02 04:08:59 24 4
gpt4 key购买 nike

我在java中迭代xml时遇到问题。我有一个根节点作为元素,元素标签内有两个子节点,但我得到的节点长度为1。任何人都可以指导我如何纠正它。我在下面提到了我的代码。

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;


public class Test {




public static void main(String arg[]) throws Exception{


String xmlRecords = "<data><employee><name>A</name><title>Manager</title><name>B</name><title>Manager</title></employee></data>";

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlRecords));

Document doc = db.parse(is);

NodeList nodes = doc.getElementsByTagName("employee");

for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);

NodeList name = element.getElementsByTagName("name");
Element line = (Element) name.item(i);
System.out.println("Name: " + getCharacterDataFromElement(line));

NodeList title = element.getElementsByTagName("title");
line = (Element) title.item(i);
System.out.println("Title: " + getCharacterDataFromElement(line));
}

}

public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}

}

结果:

Name: A
Title: Manager

预期输出:

  Name: A
Title: Manager
Name: B
Title: Manager

最佳答案

您的 XML 是

<data>
<employee>
<name>A</name>
<title>Manager</title>
<name>B</name>
<title>Manager</title>
</employee>
</data>

我建议你尝试一下

<data>
<employee>
<name>A</name>
<title>Manager</title>
</employee>
<employee>
<name>B</name>
<title>Manager</title>
</employee>
</data>

否则(正确地)只有 1 个员工节点可以打印姓名和职务

关于java - java中遍历XML节点的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33979553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com