I have a XML file, for example:
<parent value="first">
<child>Bill</child>
</parent>
I want to get at output: value=first,child=Bill That means I need attribute from parrent element and value from child element.
I tried to do something like this:
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()));
}
}
In result i have Str with "null" values.
Use like this
List<String> obj = new ArrayList<String>();
NodeList nList = doc.getElementsByTagName("parent");
for (int i = 0; i < nList.getLength(); ++i) {
NamedNodeMap map = nList.item(i).getAttributes();
for (int j = 0; j < map.getLength(); j++) {
Node attribute = map.item(j);
Node eNode = nList.item(i); // Use i value here that is the issue.
Element name = (Element) eNode;
obj.add(new String("Value = "+attribute.getNodeValue() + ",Child=" +
name.getElementsByTagName("child").item(0).getTextContent()));
}
}
Add one outer element,It works fine for multiple tags
<xml><parent value=first>
<child>Bill</child></parent> <parent value=second> <child>Steve</child>
</parent></xml>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.