1

I am trying to read a attribute of an element of a XML file and for that I am using the library jdom2 and Stax.

    private String readIncludeAll(String filePath) throws JDOMException, IOException, XMLStreamException {
        String includeAll = null;

        Document document = getStAXParsedDocument(filePath);
        Element rootNode = document.getRootElement();
        logger.info("ROOT: "+rootNode );
        List <Element> children=rootNode.getChildren();
        for(int i=0;i<children.size();i++){
            logger.info("CHILDREN:" +children.get(i).toString());
        }
        Element includeElement=rootNode.getChild("includeAll");
        logger.info("INCLUDE ELEMENT: "+includeElement);
       // includeAll=includeElement.getAttributeValue("path");
        //logger.info("VALOR DE PATH: "+includeAll);
        return includeAll;
    }

    private Document getStAXParsedDocument(final String fileName) throws JDOMException, FileNotFoundException, XMLStreamException {
            XMLInputFactory factory = XMLInputFactory.newFactory();
            XMLEventReader reader = factory.createXMLEventReader(new FileReader(fileName));
            StAXEventBuilder builder = new StAXEventBuilder();
        return builder.build(reader);
    }

I've tried printing in the console the children of the root element and includeAll is indeed a child of root element. Why is it being returned as NULL?

ROOT: [Element: <databaseChangeLog [Namespace: http://www.liquibase.org/xml/ns/dbchangelog]/>]
CHILDREN:[Element: <includeAll [Namespace: http://www.liquibase.org/xml/ns/dbchangelog]/>]
INCLUDE ELEMENT: null
Fabio
  • 343
  • 1
  • 6
  • 17
  • Instead of `rootNode.getChild("includeAll")` I guess you need to use an overload that allows you to pass in both the local name `includeAll` as well as the namespace URI `http://www.liquibase.org/xml/ns/dbchangelog`. – Martin Honnen Jun 30 '21 at 16:22
  • @MartinHonnen sorry I didn't understand – Fabio Jul 01 '21 at 08:59

1 Answers1

0

Use the overload of getChild that takes a local name and a namespace http://www.jdom.org/docs/apidocs/org/jdom2/Element.html#getChild(java.lang.String,%20org.jdom2.Namespace) i.e. rootNode.getChild("includeAll", Namespace.get("http://www.liquibase.org/xml/ns/dbchangelog"))

Martin Honnen
  • 160,499
  • 6
  • 90
  • 110