Reputation: 2761
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?
Upvotes: 2
Views: 1732
Reputation: 1
for (int i = 0; i < nl2.getLength(); i++) {
Node nt = nl2.item(i);
if (nt.getFirstChild() != null) {
String text = nt.getFirstChild().getNodeValue();
System.out.println(text);
}
}
Upvotes: 0
Reputation: 86774
You are handling ALL the child nodes of string-array
, including the text nodes before and after the item
nodes. Try
int pos = 0;
for(int i=0; i<nl2.getLength();i++){
Node n = nl2.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE)
{
pos++;
String text=n.getTextContent();
System.out.println(pos + text);
}
}
This will skip non-Element children of string-array
.
Upvotes: 2
Reputation: 8881
you need to do a trim() on getTextContent() e.g.
String text=nl2.item(i).getTextContent().trim();
Upvotes: 0