1

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 ?

1 Answer 1

1

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()");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.