XPath 如何处理 XML 名称空间?
How does XPath deal with XML namespaces?
XPath 如何处理 XML 命名空间?
如果我用
/IntuitResponse/QueryResponse/Bill/Id
为了解析下面的 XML 文档,我得到了 0 个节点。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<IntuitResponse xmlns="http://schema.intuit.com/finance/v3"
time="2016-10-14T10:48:39.109-07:00">
<QueryResponse startPosition="1" maxResults="79" totalCount="79">
<Bill domain="QBO" sparse="false">
<Id>=1</Id>
</Bill>
</QueryResponse>
</IntuitResponse>
但是,我没有在 XPath 中指定名称空间(即 http://schema.intuit.com/finance/v3
不是路径的每个标记的前缀)。如果我不明确告诉它,XPath 如何知道我想要哪个 Id
?我想在这种情况下(因为只有一个名称空间)XPath 可以完全忽略 xmlns
。但是如果有多个命名空间,事情就会变得很糟糕。
在 XPath 中定义命名空间(推荐)
XPath 本身没有办法将命名空间前缀与命名空间绑定。此类设施由托管图书馆提供。
建议您使用这些工具并定义命名空间前缀,然后可以根据需要使用这些前缀来限定 XML 元素和属性名称。
下面是 XPath 主机提供的一些机制,用于指定命名空间前缀绑定到命名空间 URI。
(OP 的原始 XPath,/IntuitResponse/QueryResponse/Bill/Id
,已被省略为 /IntuitResponse/QueryResponse
。)
C#:
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("i", "http://schema.intuit.com/finance/v3");
XmlNodeList nodes = el.SelectNodes(@"/i:IntuitResponse/i:QueryResponse", nsmgr);
Java (SAX):
NamespaceSupport support = new NamespaceSupport();
support.pushContext();
support.declarePrefix("i", "http://schema.intuit.com/finance/v3");
Java (XPath):
xpath.setNamespaceContext(new NamespaceContext() {
public String getNamespaceURI(String prefix) {
switch (prefix) {
case "i": return "http://schema.intuit.com/finance/v3";
// ...
}
});
- 记得打电话
DocumentBuilderFactory.setNamespaceAware(true)
.
- 另请参阅:
Java XPath: Queries with default namespace xmlns
Java脚本:
见Implementing a User Defined Namespace Resolver:
function nsResolver(prefix) {
var ns = {
'i' : 'http://schema.intuit.com/finance/v3'
};
return ns[prefix] || null;
}
document.evaluate( '/i:IntuitResponse/i:QueryResponse',
document, nsResolver, XPathResult.ANY_TYPE,
null );
请注意,如果默认命名空间定义了关联的命名空间前缀,则使用 Document.createNSResolver()
返回的 nsResolver()
可以避免对客户 nsResolver()
.
的需求
Perl (LibXML):
my $xc = XML::LibXML::XPathContext->new($doc);
$xc->registerNs('i', 'http://schema.intuit.com/finance/v3');
my @nodes = $xc->findnodes('/i:IntuitResponse/i:QueryResponse');
Python (lxml):
from lxml import etree
f = StringIO('<IntuitResponse>...</IntuitResponse>')
doc = etree.parse(f)
r = doc.xpath('/i:IntuitResponse/i:QueryResponse',
namespaces={'i':'http://schema.intuit.com/finance/v3'})
Python (ElementTree):
namespaces = {'i': 'http://schema.intuit.com/finance/v3'}
root.findall('/i:IntuitResponse/i:QueryResponse', namespaces)
Python (Scrapy):
response.selector.register_namespace('i', 'http://schema.intuit.com/finance/v3')
response.xpath('/i:IntuitResponse/i:QueryResponse').getall()
PhP:
改编自@Tomalak's answer using DOMDocument:
$result = new DOMDocument();
$result->loadXML($xml);
$xpath = new DOMXpath($result);
$xpath->registerNamespace("i", "http://schema.intuit.com/finance/v3");
$result = $xpath->query("/i:IntuitResponse/i:QueryResponse");
另见 。
Ruby (Nokogiri):
puts doc.xpath('/i:IntuitResponse/i:QueryResponse',
'i' => "http://schema.intuit.com/finance/v3")
请注意,Nokogiri 支持删除命名空间,
doc.remove_namespaces!
但看到下面的警告阻止了 XML 命名空间的失败。
VBA:
xmlNS = "xmlns:i='http://schema.intuit.com/finance/v3'"
doc.setProperty "SelectionNamespaces", xmlNS
Set queryResponseElement =doc.SelectSingleNode("/i:IntuitResponse/i:QueryResponse")
VB.NET:
xmlDoc = New XmlDocument()
xmlDoc.Load("file.xml")
nsmgr = New XmlNamespaceManager(New XmlNameTable())
nsmgr.AddNamespace("i", "http://schema.intuit.com/finance/v3");
nodes = xmlDoc.DocumentElement.SelectNodes("/i:IntuitResponse/i:QueryResponse",
nsmgr)
SoapUI (doc):
declare namespace i='http://schema.intuit.com/finance/v3';
/i:IntuitResponse/i:QueryResponse
xmlstarlet:
-N i="http://schema.intuit.com/finance/v3"
XSLT:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:i="http://schema.intuit.com/finance/v3">
...
一旦声明了名称空间前缀,就可以编写 XPath 来使用它:
/i:IntuitResponse/i:QueryResponse
击败 XPath 中的名称空间(不推荐)
另一种方法是编写针对 local-name()
:
进行测试的谓词
/*[local-name()='IntuitResponse']/*[local-name()='QueryResponse']
或者,在 XPath 2.0 中:
/*:IntuitResponse/*:QueryResponse
以这种方式踢边命名空间可行,但不推荐,因为它
未指定完整的 element/attribute 名称。
无法区分不同的 element/attribute 名称
命名空间(命名空间的目的)。请注意,可以通过添加额外的谓词来显式检查命名空间 URI1:
来解决此问题
/*[ namespace-uri()='http://schema.intuit.com/finance/v3'
and local-name()='IntuitResponse']
/*[ namespace-uri()='http://schema.intuit.com/finance/v3'
and local-name()='QueryResponse']
1感谢 Daniel Haley 的 namespace-uri()
注释。
过于冗长。
我在 google sheet 中使用 /*[name()='...']
从维基数据中获取一些计数。我有一个这样的table
thes WD prop links items
NOM P7749 3925 3789
AAT P1014 21157 20224
列links
和items
中的公式是
=IMPORTXML("https://query.wikidata.org/sparql?query=SELECT(COUNT(*)as?c){?item wdt:"&$B14&"[]}","//*[name()='literal']")
=IMPORTXML("https://query.wikidata.org/sparql?query=SELECT(COUNT(distinct?item)as?c){?item wdt:"&$B14&"[]}","//*[name()='literal']")
分别。 SPARQL 查询碰巧没有任何空格...
我看到在 Xml Namespace breaking my xpath! 中使用 name()
而不是 local-name()
,但由于某些原因 //*:literal
不起作用。
XPath 如何处理 XML 命名空间?
如果我用
/IntuitResponse/QueryResponse/Bill/Id
为了解析下面的 XML 文档,我得到了 0 个节点。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<IntuitResponse xmlns="http://schema.intuit.com/finance/v3"
time="2016-10-14T10:48:39.109-07:00">
<QueryResponse startPosition="1" maxResults="79" totalCount="79">
<Bill domain="QBO" sparse="false">
<Id>=1</Id>
</Bill>
</QueryResponse>
</IntuitResponse>
但是,我没有在 XPath 中指定名称空间(即 http://schema.intuit.com/finance/v3
不是路径的每个标记的前缀)。如果我不明确告诉它,XPath 如何知道我想要哪个 Id
?我想在这种情况下(因为只有一个名称空间)XPath 可以完全忽略 xmlns
。但是如果有多个命名空间,事情就会变得很糟糕。
在 XPath 中定义命名空间(推荐)
XPath 本身没有办法将命名空间前缀与命名空间绑定。此类设施由托管图书馆提供。
建议您使用这些工具并定义命名空间前缀,然后可以根据需要使用这些前缀来限定 XML 元素和属性名称。
下面是 XPath 主机提供的一些机制,用于指定命名空间前缀绑定到命名空间 URI。
(OP 的原始 XPath,/IntuitResponse/QueryResponse/Bill/Id
,已被省略为 /IntuitResponse/QueryResponse
。)
C#:
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("i", "http://schema.intuit.com/finance/v3");
XmlNodeList nodes = el.SelectNodes(@"/i:IntuitResponse/i:QueryResponse", nsmgr);
Java (SAX):
NamespaceSupport support = new NamespaceSupport();
support.pushContext();
support.declarePrefix("i", "http://schema.intuit.com/finance/v3");
Java (XPath):
xpath.setNamespaceContext(new NamespaceContext() {
public String getNamespaceURI(String prefix) {
switch (prefix) {
case "i": return "http://schema.intuit.com/finance/v3";
// ...
}
});
- 记得打电话
DocumentBuilderFactory.setNamespaceAware(true)
. - 另请参阅: Java XPath: Queries with default namespace xmlns
Java脚本:
见Implementing a User Defined Namespace Resolver:
function nsResolver(prefix) {
var ns = {
'i' : 'http://schema.intuit.com/finance/v3'
};
return ns[prefix] || null;
}
document.evaluate( '/i:IntuitResponse/i:QueryResponse',
document, nsResolver, XPathResult.ANY_TYPE,
null );
请注意,如果默认命名空间定义了关联的命名空间前缀,则使用 Document.createNSResolver()
返回的 nsResolver()
可以避免对客户 nsResolver()
.
Perl (LibXML):
my $xc = XML::LibXML::XPathContext->new($doc);
$xc->registerNs('i', 'http://schema.intuit.com/finance/v3');
my @nodes = $xc->findnodes('/i:IntuitResponse/i:QueryResponse');
Python (lxml):
from lxml import etree
f = StringIO('<IntuitResponse>...</IntuitResponse>')
doc = etree.parse(f)
r = doc.xpath('/i:IntuitResponse/i:QueryResponse',
namespaces={'i':'http://schema.intuit.com/finance/v3'})
Python (ElementTree):
namespaces = {'i': 'http://schema.intuit.com/finance/v3'}
root.findall('/i:IntuitResponse/i:QueryResponse', namespaces)
Python (Scrapy):
response.selector.register_namespace('i', 'http://schema.intuit.com/finance/v3')
response.xpath('/i:IntuitResponse/i:QueryResponse').getall()
PhP:
改编自@Tomalak's answer using DOMDocument:
$result = new DOMDocument();
$result->loadXML($xml);
$xpath = new DOMXpath($result);
$xpath->registerNamespace("i", "http://schema.intuit.com/finance/v3");
$result = $xpath->query("/i:IntuitResponse/i:QueryResponse");
另见
Ruby (Nokogiri):
puts doc.xpath('/i:IntuitResponse/i:QueryResponse',
'i' => "http://schema.intuit.com/finance/v3")
请注意,Nokogiri 支持删除命名空间,
doc.remove_namespaces!
但看到下面的警告阻止了 XML 命名空间的失败。
VBA:
xmlNS = "xmlns:i='http://schema.intuit.com/finance/v3'"
doc.setProperty "SelectionNamespaces", xmlNS
Set queryResponseElement =doc.SelectSingleNode("/i:IntuitResponse/i:QueryResponse")
VB.NET:
xmlDoc = New XmlDocument()
xmlDoc.Load("file.xml")
nsmgr = New XmlNamespaceManager(New XmlNameTable())
nsmgr.AddNamespace("i", "http://schema.intuit.com/finance/v3");
nodes = xmlDoc.DocumentElement.SelectNodes("/i:IntuitResponse/i:QueryResponse",
nsmgr)
SoapUI (doc):
declare namespace i='http://schema.intuit.com/finance/v3';
/i:IntuitResponse/i:QueryResponse
xmlstarlet:
-N i="http://schema.intuit.com/finance/v3"
XSLT:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:i="http://schema.intuit.com/finance/v3">
...
一旦声明了名称空间前缀,就可以编写 XPath 来使用它:
/i:IntuitResponse/i:QueryResponse
击败 XPath 中的名称空间(不推荐)
另一种方法是编写针对 local-name()
:
/*[local-name()='IntuitResponse']/*[local-name()='QueryResponse']
或者,在 XPath 2.0 中:
/*:IntuitResponse/*:QueryResponse
以这种方式踢边命名空间可行,但不推荐,因为它
未指定完整的 element/attribute 名称。
无法区分不同的 element/attribute 名称 命名空间(命名空间的目的)。请注意,可以通过添加额外的谓词来显式检查命名空间 URI1:
来解决此问题/*[ namespace-uri()='http://schema.intuit.com/finance/v3' and local-name()='IntuitResponse'] /*[ namespace-uri()='http://schema.intuit.com/finance/v3' and local-name()='QueryResponse']
1感谢 Daniel Haley 的
namespace-uri()
注释。过于冗长。
我在 google sheet 中使用 /*[name()='...']
从维基数据中获取一些计数。我有一个这样的table
thes WD prop links items
NOM P7749 3925 3789
AAT P1014 21157 20224
列links
和items
中的公式是
=IMPORTXML("https://query.wikidata.org/sparql?query=SELECT(COUNT(*)as?c){?item wdt:"&$B14&"[]}","//*[name()='literal']")
=IMPORTXML("https://query.wikidata.org/sparql?query=SELECT(COUNT(distinct?item)as?c){?item wdt:"&$B14&"[]}","//*[name()='literal']")
分别。 SPARQL 查询碰巧没有任何空格...
我看到在 Xml Namespace breaking my xpath! 中使用 name()
而不是 local-name()
,但由于某些原因 //*:literal
不起作用。