如何在java中从XML中获取父元素属性和子值?
我有一个XML文件,例如:
<parent value="first">
<child>Bill</child>
</parent>
我想得到输出:value=first,child=Bill 这意味着我需要parrent元素的属性和子元素的值
我试着这样做:
List<Str> obj = new ArrayList<Str>();
NodeList nList = doc.getElementsByTagName("parent");
for (int i = 0; i < nList.getLength(); ++i) {
Element attrElement = (Element) nList.item(i);
NamedNodeMap map = attrElement.getAttributes();
for (int j = 0; j < map.getLength(); j++) {
Node attribute = map.item(j);
Node eNode = nList.item(j);
Element name = (Element) eNode;
obj.add(new Str(attribute.getNodeValue(), name.getElementsByTagName("child").item(0).getTextContent()));
}
}
结果我得到了带有“null”值的Str
# 1 楼答案
像这样使用
添加一个外部元素,它可以很好地用于多个标记