I am trying to parse a xml file using dom parser. The xml fles contains lots of missing tags.
What i want to do is that , if i get any missing tag( like in example below 2nd artist tag do not contain image tag) i want to set String image as some value like “na”, so that i can put values in an array or a list.
Below is example
<list>
<artist>
<id>1</id>
<name>name1</name>
<image>name1.jpg</image>
</artist>
<artist>
<id>2</id>
<name>name2</name>
</artist>
</list>
My current code :
NodeList list = element.getElementsByTagName("artist");
if (list != null && list.getLength() > 0) {
for (int i = 0; i < list.getLength(); i++) {
Node item = list.item(i);
NodeList properties = item.getChildNodes();
for (int j = 0; j < properties.getLength(); j++) {
Node property = properties.item(j);
String name = property.getNodeName();
if (name.equalsIgnoreCase("__id")) {
try {
String strTitle = property.getFirstChild()
.getNodeValue();
System.out.println(strTitle);
} catch (NullPointerException e) {
// TODO: handle exception
System.out.println("Null ID");
}
}
else if (name.equalsIgnoreCase("__name")) {
try {
String strTitle = property.getFirstChild()
.getNodeValue();
System.out.println(strTitle);
} catch (NullPointerException e) {
// TODO: handle exception
System.out.println("Null Name");
}
}
else if (name.equalsIgnoreCase("__image")) {
try {
String strTitle = property.getFirstChild()
.getNodeValue();
System.out.println(strTitle);
} catch (NullPointerException e) {
// TODO: handle exception
System.out.println("Null Image");
}
}
}`
Add a String variable set to your default, assigned just before you enter the loop that parses child tags of artist. Then within your loop, if you find an image child, replace that String variable with the provided value.
Edit: code based on the original: