简体   繁体   中英

XPath not reading xml tag with namespace

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?

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()");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM