Home > Back-end >  XPath not reading xml tag with namespace
XPath not reading xml tag with namespace

Time:03-01

hi i am trying to read a xml which have namespace defined and some tags are with namespaces. But namespace tags always give empty value when i use XPath to read those tags.

Sample XML

<?xml version="1.0" encoding="UTF-8"?>
<Employees xmlns:ULAD="http://www.datamodelextension.org/Schema/ULAD">
<EXTENSION>
    <OTHER>
        <ULAD:HMDAGenderType>Male</ULAD:HMDAGenderType>
    </OTHER>
</EXTENSION>
</Employees>

Sample Java Program to read ULAD:HMDAGenderType

public static void main(String args[]) throws XPathExpressionException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try {
  DocumentBuilder builder = factory.newDocumentBuilder();
  Document doc = builder.parse("C:\\test.xml");
  XPathFactory xpathFactory = XPathFactory.newInstance();
  XPath xpath = xpathFactory.newXPath();
  XPathExpression expr = xpath.compile("/Employees/EXTENSION/OTHER/ULAD:HMDAGenderType");
  System.out.println("Gender :: "   expr.evaluate(doc, XPathConstants.STRING));
} catch (ParserConfigurationException | SAXException | IOException e) {
  e.printStackTrace();
}
}

Output :: null

Expected Output :: Male

How to read such tags ?

CodePudding user response:

Try using XPath local-name()
Instead of

XPathExpression expr = xpath.compile("/Employees/EXTENSION/OTHER/ULAD:HMDAGenderType");

Please try

XPathExpression expr = xpath.compile("//*[local-name()='HMDAGenderType']");

And to get the text attribute value directly you can use this XPath:

XPathExpression expr = xpath.compile("//*[local-name()='HMDAGenderType']/text()");
  • Related