Reputation: 774
Hi I am trying to read a XML document using Java. I want to check if all the tags exist before trying to get the content in it.
I have something like this;
String ToolVersion;
if (element.getElementsByTagName("ToolVersion").getLength() > 0) {
ToolVersion = element.getElementsByTagName("ToolVersion").item(0).getTextContent(); }
I have over 20 XML tags, is there a way to do this without having 20 "IF" conditions ?
Upvotes: 1
Views: 673
Reputation: 1523
You can do it using jaxb. It provides marshaller and demarshaller which will help you in verifying whether tags exist or not.
Upvotes: 1
Reputation: 377
Some code to think about.
String getData(Element e, String tagName){
if (e.getElementsByTagName(tagName).getLength() > 0) {
return e.getElementsByTagName(tagName).item(0).getTextContent();
} else return null;
}
BODY
List<String> elementsList = Arrays.asList("ToolVersion", "ToolName", "SomethingElse");
Element e;
String tagData;
for(String tagName : elementsList){
tagData = getData(e, tagName);
//do something here
}
Upvotes: 2