문제

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"));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top