Frage

I have code that searches XML Documents (org.w3c.dom) using namespace-aware XPath. I am having issues with adding elements to the document and then being able to find them via the XPath.

If I add the elements and search using the XPath I do not get any result. However, if I convert the Document to a String and reparse to a Document, the XPath finds the element.

I create the XPath as follows:

String myXPathQuery = "/ns1:element1/ns2:element2/ns3:element3";
XPathFactory fact = XPathFactory.newInstance();
XPath xpath = fact.newXPath();
xpath.setNamespaceContext(myNSContext);
XPathExpression myXPathExpression = xpath.compile(myXPathQuery);

I am adding the element as follows:

Document doc = ...;
Element elementToWhichToAdd = ...; // this is "ns2:element2"

Element newElement = doc.createElement("ns3:element3");
elementToWhichToAdd.appendChild(newElement);

If I run the above XPath against this Document it doesn't find anything. But if I reparse the Document the XPath works.

What am I missing?

EDIT

As part of the process by which I update the document I add the Namespace if it does not exist (it usually does not).

Element rootElement = doc.getDocumentElement();
NamedNodeMap map = rootElement.getAttributes();
if (map.getNamedItem("xmlns:ns3") == null)
     rootElement.setAttributeNS("http://www.w3.org/2000/xmlns", "xmlns:ns3",
            "urn:exo:/path/to/xsd/in/jar");
War es hilfreich?

Lösung

Element newElement = doc.createElement("ns3:element3");

createElement is a DOM level 1 method that is not namespace aware - its JavaDoc says that it returns

A new Element object with the nodeName attribute set to tagName, and localName, prefix, and namespaceURI set to null.

You need to create the new elements using the DOM level 2 createElementNS instead

Element newElement = doc.createElementNS("urn:exo:/path/to/xsd/in/jar", "ns3:element3");

(or whatever is the correct namespace URI that corresponds to ns3, you could get it directly from the namespace context using myNSContext.getNamespaceURI("ns3")).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top