简体   繁体   中英

JDOM2 Namespace with prefix 'uml' has not been declared

I am trying to get an Element via the XPathExpression option from JDOM.

My code looks like this:

public static Element getElement(Document doc)
{
    XPathFactory xpfac = XPathFactory.instance();
    XPathExpression<Element> xp = xpfac.compile("//uml:Model/packagedElement[@name='Content']", Filters.element());
    return xp.evaluateFirst(doc);
}

Sadly i get the following error:

java.lang.IllegalArgumentException: Namespace with prefix 'uml' has not been declared.

My document starts like this:

<?xml version='1.0' encoding='UTF-8'?>
<xmi:XMI xmi:version='2.1' xmlns:uml='http://www.omg.org/spec/UML/20090901'...

So in my opinion the namespace is declared. If i check the xpath expression with a tool for the given document, the element is found.

Thats how i created the document:

public static Document readXML(File file)
{
    Document doc = null;
    try {
        doc = new SAXBuilder().build(file);
    } catch (JDOMException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return doc;
}

So, wheres the error? How can the XpathExpression find the element "//uml:Model/packagedElement[@name='Content']" ?

Best regards

The namespace is declared in the XML, but you also have to register it for the XPath query .

XPathExpression<Element> xp =
    xpfac.compile("//uml:Model/packagedElement[@name='Content']",
        Filters.element(),
        null,
        Namespace.getNamespace("uml", "http://www.omg.org/spec/UML/20090901"));

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