I'm new into java and xml parsing processes, so i got stucked. My xml is:
<?xml version="1.0" encoding="utf-16"?>
<LauncherInfo xmlns:xsi="http://ift.tt/ra1lAU" xmlns:xsd="http://ift.tt/tphNwY" xmlns="http://ift.tt/1vC7NUZ" hash="d8bf41f6053ab2df28704dfcda443f9199546d3b">
<File Name="parakstitais.edoc" Location="vieta_kur_saglabat" />
<Action xsi:type="CreateNewSignAction">
<FileReferences>
<FileReference Name="Document1.doc" Address="some url" />
<FileReference Name="Scan7.pdf" Address="some url" />
<FileReference Name="Scan8.pdf" Address="some url" />
</FileReferences>
</Action>
</LauncherInfo>
and my goal is to extract all Action part, so it should be like:
<Action xsi:type="CreateNewSignAction">
<FileReferences>
<FileReference Name="Document1.doc" Address="some url" />
<FileReference Name="Scan7.pdf" Address="some url" />
<FileReference Name="Scan8.pdf" Address="some url" />
</FileReferences>
</Action>
Currently my Java code is
public static void main(String[] args) throws ParserConfigurationException,
MalformedURLException, SAXException, IOException,
TransformerException, XPathExpressionException {
String URL = "my xml URL";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new URL(URL).openStream());
URL namespaceURL = new URL("http://ift.tt/ra1lAU");
String namespace = "xmlns:xsi="+namespaceURL.toString();
Element messages = doc.createElementNS(namespace, "messages");
doc.appendChild(messages);
XPath xPath = XPathFactory.newInstance().newXPath();
Node result = (Node) xPath.evaluate("LauncherInfo/Action", doc,
XPathConstants.NODE);
System.out.println(nodeToString(result));
System.out.println("...");
}
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());
}
When launching an error appears: ERROR: 'Namespace for prefix 'xsi' has not been declared.'. I suppose that something with namespace declaration should be done. Is there any way to declare namepace URI in xpath query, or there is a better solution?
No comments:
Post a Comment