我有一个在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
答案 0 :(得分:2)
您的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个员工节点,您打印名称和标题
答案 1 :(得分:0)
一些事情:只有一个151 - 160
节点,所以你的循环迭代一次。考虑向String添加第二个节点:
<employee>
其次,对于String xmlRecords = "<data><employee><name>A</name><title>Manager</title></employee>" +
"<employee><name>B</name><title>Manager</title></employee></data>";
和<name>
,不要在这些内部节点上进行迭代,因为每个员工中只有一个。因此,请使用零而不是<title>
。这当然取决于上面的父节点更改。
i
按上述方法产生您想要的结果:
NodeList name = element.getElementsByTagName("name");
Element line = (Element) name.item(0);
NodeList title = element.getElementsByTagName("title");
line = (Element) title.item(0);