0

I made an XML document and queried it using xpath. Here's a snippet of the XML doc. The entire thing is pretty long.

<?xml version="1.0" encoding="UTF-8"?>
<ligue name="Premier League" id="P_L"
xmlns="https://www.w3schools.com" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="https://www.w3schools.com ligue.xsd"
>
    <equipe name='Arsenal'><!-- DONE-->
        <manager>
            <nom>Arteta</nom>
            <prenom>Mikel</prenom>
            <date_de_debut>2019-12-20</date_de_debut>
            <date_de_naissance>1982-03-26</date_de_naissance>
            <salaire>8300000</salaire>
        </manager>

Here's my Java program made to execute one simple xpath expression.

public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse("ligue.xml");
    XPathFactory xpathfactory = XPathFactory.newInstance();
    XPath xpath = xpathfactory.newXPath();
    XPathExpression expr=xpath.compile("/ligue/equipe[@name='Arsenal']/manager/nom/text()");
    NodeList result=(NodeList) expr.evaluate(doc,XPathConstants.NODESET);
    System.out.println("length is "+result.getLength());
    for (int i = 0; i < result.getLength(); i++) {
        System.out.println(result.item(i).getNodeValue());
        }
        
    }

When I run the Java program it doesn't give me the name of the manager which is Arteta. However if I unbind the XML document to the xsd by removing: xmlns="https://www.w3schools.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://www.w3schools.com ligue.xsd" It runs correctly. I read online about namespaces and how it is causing the error. I tried using a prefix which I then added in the xpath expression and nothing changed. Any help will be duly appreciated.

rgettman
  • 176,041
  • 30
  • 275
  • 357

0 Answers0