I would like to parse this xml file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="descripciones">
<item>one</item>
<item>two</item>
</string-array>
</resources>
The original file is a much bigger array.
Here is my code:
builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(new FileInputStream("descripciones.xml"));
Element rootElement = document.getDocumentElement();
NodeList nl = rootElement.getElementsByTagName("string-array");
Element nl1 =(Element) nl.item(0);
NodeList nl2=nl1.getChildNodes();
for(int i=0; i<nl2.getLength();i++){
String text=nl2.item(i).getTextContent();
System.out.println(i+text);
}
The problem is when I print the result I get every each line I get an empty item:
1 one
2
3 two
4
Is there a way to fix it? Is there a better way to extract the data between tags?
You are handling ALL the child nodes of
string-array, including the text nodes before and after theitemnodes. TryThis will skip non-Element children of
string-array.