Initially I have this file.
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<owl:Class />
<owl:Class />
<owl:ObjectProperty />
<Situation:Situation rdf:about"http://localhost/rdf#situa0">
<Situation:composedBy />
</Situation:Situation>
</rdf:RDF>
My goal is to extract the node Situation and its content using xPath "RDF/Situation" ...
<Situation:Situation rdf:about"http://localhost/rdf#situa0">
<Situation:composedBy />
</Situation:Situation>
I found a good example to work with in Java How to extract a complete XML block.
I changed names of tags to my own since I use namespaces and predefined tags.
Here's my code
public static void main(String... args) throws Exception {
String xml = "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><owl:Class /><owl:Class /><owl:ObjectProperty /><Situation:Situation rdf:about=\"http://localhost/rdf#situa0\" ><Situation:composedBy /></Situation:Situation></rdf:RDF>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document doc = dbf.newDocumentBuilder().parse(
new InputSource(new StringReader(xml)));
XPath xPath = XPathFactory.newInstance().newXPath();
Node result = (Node) xPath.evaluate("RDF/Situation", doc, XPathConstants.NODE);
System.out.println(nodeToString(result));
}
private static String nodeToString(Node node) throws TransformerException {
StringWriter buf = new StringWriter();
Transformer xform = TransformerFactory.newInstance().newTransformer();
xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
xform.transform(new DOMSource(node), new StreamResult(buf));
return (buf.toString());
}
My goal is 90% achieved but I have a problem, the Situation tag has an attribute about with a prefix rdf (the code works if I remove the prefix, and even if I added rdf xmlns in the root element)
<Situation:Situation rdf:about="http://localhost/rdf#situa0">
I got this error
ERROR: 'The namespace prefix' rdf 'has not been declared.'
Exception in thread "main" javax.xml.transform.TransformerException: java.lang.RuntimeException: Namespace prefix 'rdf' has not been declared.
com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform at (Unknown Source)
com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform at (Unknown Source)
I added dbf.setNamespaceAware(true)
as @ Ian Roberts mentioned, so I got other errors asking for owl & Situation namespaces, after adding it in the root tag, I got nothing in output and without errors. What is the problem ?? The problem was that the variable result, this time is null, so there's a problem with the xPath query..
I tried to see in another place the result of the query and it worked fine in an online xPath tester.
So what is the problem ??
Is there any other way to do like this job.???
thx :)