0

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.

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. But there is a problem. I have more than one parent. Attribute changes, but child name stays like first. I wanted if <parent value="first"> <child>Bill</child> </parent> <parent value="second"> <child>Steve</child> </parent> And the result I get: 1) value=first,child=Bill 2) value=second,child=Bill but value=second,child=Steve should be.
I copied yours xml. In both cases I get "Child = Bill"
Please see updated code near " Use i value instead of j that is the issue. "

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.