当我的XML看起来像这样(没有xmlns
)时,我就可以像/workbook/sheets/sheet[1]
一样用XPath轻松地查询它
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<workbook>
<sheets>
<sheet name="Sheet1" sheetId="1" r:id="rId1"/>
</sheets>
</workbook>
但是当它看起来像这样的时候我就不能
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets>
<sheet name="Sheet1" sheetId="1" r:id="rId1"/>
</sheets>
</workbook>
有什么想法吗?
发布于 2018-01-30 21:45:46
如果您使用的是Spring,那么它已经包含org.springframework.util.xml.SimpleNamespaceContext.
import org.springframework.util.xml.SimpleNamespaceContext;
...
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
SimpleNamespaceContext nsc = new SimpleNamespaceContext();
nsc.bindNamespaceUri("a", "http://some.namespace.com/nsContext");
xpath.setNamespaceContext(nsc);
XPathExpression xpathExpr = xpath.compile("//a:first/a:second");
String result = (String) xpathExpr.evaluate(object, XPathConstants.STRING);
发布于 2011-06-18 03:20:32
确保在XSLT中引用该命名空间
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" >
发布于 2019-02-07 07:40:14
令人惊讶的是,如果我不设置factory.setNamespaceAware(true);
,那么您提到的xpath在使用和不使用名称空间的情况下都可以工作。您只是不能选择“指定了名称空间”的对象,而只能选择通用的xpath。去想一想。所以这可能是一种选择:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
https://stackoverflow.com/questions/6390339
复制相似问题