0

I want to read a tag value from XML file (e.g. my.xml). I know the absolute path (e.g. /Document/a/b/c to that tag, so I don't want to iterate. Following code doesn't work

    private void getXMLValue(String[] args) {
    String filename=args[1];
    String pathName=args[2];
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new File(filename));
        XPathFactory xfac = XPathFactory.newInstance();
        XPath xpath = xfac.newXPath();
        
        Element el = (Element) xpath.evaluate(pathName, doc, XPathConstants.NODE);
        if (el != null)
            logger.info("found from xpath: "+ el.getTextContent());         
    } catch (Exception e) {
        logger.error(filename, e);
    }
}

XML-File is like:

<?xml version="1.0" encoding="utf-8"?> 
<Document> 
<a> 
<b> 
<aa>MsgId-0815</aa> 
<bb>2019-11-21T09:30:47.000Z</bb> 
<c>3</c>
</b>
</a>
</Document>

What am I doing wrong, when I call the method with following parameters: my.xml /Document/a/b/c?

Martin Müller
  • 122
  • 3
  • 17

0 Answers0