문제

I have an xml document as a string without any namespace and I want to parse it using Java, JDOM and XPath, and create a object tree. Since XPAth always requires a prefix and a namespace to query, I added namespace and a prefix to the root and then later to the node I want to get, but I see Xpath requires a namespace in every node in the document but only in the root.

So in the beginning is there a way to add the namespace to all of the elements in the document object so my xpath query works correct?

There should be other mistakes and bad approches in the code as well. Will be glad for any ideas.

String response="myXmlString"
ByteArrayInputStream stream = new ByteArrayInputStream(
            response.getBytes());
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(stream);
org.jdom.Element request=(org.jdom.Element) doc.getRootElement();   
request.setNamespace(Namespace.getNamespace("myNamespace"));

createRequest(request);

And then

public Request createRequest(Element requestXML) {              
Request request = new Request();
requestXML.detach();
Document doc = new Document(requestXML);
XPath xpath = XPath.newInstance(myExpression);
xpath.addNamespace("m", doc.getRootElement().getNamespaceURI());

xpath.selectSingleNode(doc);

}

this last line returns empty, it is not null but it throws jdom exception inside.

도움이 되었습니까?

해결책

XPath and XML do NOT require namespace. Go back to your original XML and remove any namespace/prefix hackery in your code.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top