How to read an array of values in an XML Node, using Java

1.1k views Asked by At

I think the question makes sense.

I have the following xml:

<?xml version="1.0"?>
<ArrayOfstring xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <string>domain\coder1</string>    
  <string>domain\coder2</string>
</ArrayOfstring>

I am trying to read the two elements into a List.

If I use:

NodeList nList = doc.getElementsByTagName("ArrayOfstring");
....
szCoder = eElement.getElementsByTagName("string").item(i).getTextContent();

In only get "domain\coder1", because my list only has a value of one. If I try using a TagName of "string", I throw a nullpointer.

Any help would be greatly appreciated.

Many thanks in advance

2

There are 2 answers

1
MGLeon On
    Node nodeString = null;
    Node itemArray = null;
    NodeList listOfStringEle = null;
    NodeList nList = doc.getElementsByTagName("ArrayOfstring");
    for (int j = 0; j < nList.getLength(); j++) {
         itemArray = nList.item(j); //here all the ArrayOfStringElements
         listOfStringEle = itemArray.getChildNodes();
         for (int i = 0; i < listOfStringEle.getLength(); i++) {
                            nodeString = listOfStringEle.item(i); //here are the <string> nodes
                        }
    }

You need to run through all the nodes. To get access to them

0
Dudleston On

Many thanks for the quick reply, last Friday. I had to change "ArrayOfstring" to be that of the ChildNode - "string"

All now works :)