How to find a XML element is empty element tag or incorrect element tag.
Let us consider the below XML string:
<?xml version="1.0" encoding="utf-8" ?>
<ags:AGSSalesDocument xmlns:ags="http://www.ags.co.uk/ns/ags">
<ags:Features>
<ags:IntInst>
<ags:SortCde>111111</ags:SortCde>
<ags:BankAcc>12345678</ags:BankAcc>
<ags:BankName />
</ags:IntInst>
</ags:Features>
</ags:AGSSalesDocument>
To fetch the element I have written a reusable method as shown below
public static String fetchElementValueFromXMLUsingXMLParser(String strXpath, String strAttributeName) {
String strXML1= null, strNodeValue = null, strXpathValue = null;
try {
//Below update to string made to make sure JAVA XML Parser works
strXML1= "<ags:AGSSalesDocument xmlns:ags="http://www.ags.co.uk/ns/ags"><ags:Features><ags:IntInst><ags:SortCde>111111</ags:SortCde> <ags:BankAcc>12345678</ags:BankAcc><ags:BankName /></ags:IntInst></ags:Features></ags:AGSSalesDocument>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder builder = null;
builder = dbf.newDocumentBuilder();
Document doc = null;
doc = builder.parse(new InputSource(new StringReader(strXML1)));
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(new NamespaceContext() {
public String getNamespaceURI(String prefix) {
return prefix.equals("ags") ? "www.ags.co.uk/ns/ags" : null;
}
public Iterator<?> getPrefixes(String val) {
return null;
}
public String getPrefix(String uri) {
return null;
}
});
Node node = null;
if (!strAttributeName.equalsIgnoreCase(""))
strXpathValue = strXpath + "/@" + strAttributeName;
else
strXpathValue = strXpath + "/text()";
node = XPathAPI.selectSingleNode(doc, strXpathValue);
NodeList nList = XPathAPI.selectNodeList(doc, strXpathValue);
System.out.println("TheLength"+String.valueOf(nList.getLength()));
if (node == null)
strNodeValue = "NULL";
else
strNodeValue = node.getNodeValue();
} catch (TransformerException e) {
throw new RuntimeException(e);
} catch (SAXException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
}
return strNodeValue;
}
public static void main(String[] args)
{
//There is no such element as SordCd
String strValue=fetchElementValueFromXMLUsingXMLParser("/ags:AGSSalesDocument/ags:Features/ags:IntInst/ags:SortCd","");
//This element is empty element Tag
String strValue1=fetchElementValueFromXMLUsingXMLParser("/ags:AGSSalesDocument/ags:Features/ags:IntInst/ags:BankName","");
}
Now whenever we debug this code for both Sortcd tag and BankName tag, we are getting the below values:
nList.getLength()=0
node=Null
Am looking to differentiate when there is empty element tag (here bankName). We would need to Return "NULL" value. When there is no such given element (here SortCd). we would need to return "NOSUCHELEMENT" value.