阿波罗的战车
您的问题是默认命名空间。查看本文,了解如何处理XPath中的命名空间:http://www.edankert.com/defaultnamespaces.html他们得出的结论之一是:因此,为了能够在(默认)命名空间中定义的XML内容上使用XPath表达式,我们需要指定命名空间前缀映射请注意,这并不意味着您必须以任何方式更改源文档(尽管您可以根据需要随意添加名称空间前缀)。听起来很奇怪吧?什么,你会做的是在你的Java代码和使用创建一个命名空间前缀映射说在你的XPath表达式的前缀。在这里,我们将创建一个映射spreadsheet到您的默认命名空间。XPathFactory factory = XPathFactory.newInstance();XPath xpath = factory.newXPath();// there's no default implementation for NamespaceContext...seems kind of silly, no?xpath.setNamespaceContext(new NamespaceContext() {
public String getNamespaceURI(String prefix) {
if (prefix == null) throw new NullPointerException("Null prefix");
else if ("spreadsheet".equals(prefix)) return "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
else if ("xml".equals(prefix)) return XMLConstants.XML_NS_URI;
return XMLConstants.NULL_NS_URI;
}
// This method isn't necessary for XPath processing.
public String getPrefix(String uri) {
throw new UnsupportedOperationException();
}
// This method isn't necessary for XPath processing either.
public Iterator getPrefixes(String uri) {
throw new UnsupportedOperationException();
}});// note that all the elements in the expression are prefixed with our namespace mapping!XPathExpression expr = xpath.compile("/spreadsheet:workbook/spreadsheet:sheets/spreadsheet:sheet[1]");// assuming you've got your XML document in a variable named doc...Node result = (Node) expr.evaluate(doc, XPathConstants.NODE);瞧...现在你已经将你的元素保存在result变量中了。警告:如果您使用标准JAXP类将XML解析为DOM,请务必调用setNamespaceAware(true)您的DocumentBuilderFactory。否则,此代码将无法正常工作!