我是java和xml解析进程的新成员,所以我陷入了困境。我的XML是:前缀'xsi'的命名空间尚未声明
<?xml version="1.0" encoding="utf-16"?>
<LauncherInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.microsoft.com/edoc/2009/Launcher.xml" 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>
,我的目标是提取所有行动的一部分,所以它应该是这样的:
<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>
目前我的Java代码
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://www.w3.org/2001/XMLSchema-instance");
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());
}
当启动一个错误出现: 错误:'名称空间的前缀'xsi'尚未声明。'。 我想应该做一些与命名空间声明。有没有什么办法在xpath查询中声明名称空间URI,或者有更好的解决方案?
我对Java没有太多的了解,但是您可能需要做的是在'Action中包含'xmlns:xsi =“http://www.w3.org/2001/XMLSchema-instance”''你输出的元素。 – 2014-11-04 19:12:43