xmllint无法正确使用xpath查询 [英] xmllint failing to properly query with xpath
问题描述
我正在尝试查询adium生成的xml文件. xmlwf说它格式正确.通过使用xmllint的调试选项,我得到以下信息:
I'm trying to query an xml file generated by adium. xmlwf says that it's well formed. By using xmllint's debug option i get the following:
$ xmllint --debug doc.xml
DOCUMENT
version=1.0
encoding=UTF-8
URL=doc.xml
standalone=true
ELEMENT chat
default namespace href=http://purl.org/net/ulf/ns/0.4-02
ATTRIBUTE account
TEXT
content=foo@bar.com
ATTRIBUTE service
TEXT compact
content=MSN
TEXT compact
content=
ELEMENT event
ATTRIBUTE type
一切似乎都可以解析.但是,当我尝试查询最简单的内容时,却什么也没得到:
Everything seems to parse just fine. However, when I try to query even the simplest things, I don't get anything:
$ xmllint --xpath '/chat' doc.xml
XPath set is empty
发生了什么事?使用xpath运行该完全相同的查询将返回正确的结果(但是结果之间没有换行符).我是在做错什么还是xmllint不能正常工作?
What's happening? Running that exact same query using xpath returns the correct results (however with no newline between results). Am I doing something wrong or is xmllint just not working properly?
这是显示相同行为的xml的较短的匿名版本:
Here's a shorter, anonymized version of the xml that shows the same behavior:
<?xml version="1.0" encoding="UTF-8" ?>
<chat xmlns="http://purl.org/net/ulf/ns/0.4-02" account="foo@bar.com" service="MSN">
<event type="windowOpened" sender="foo@bar.com" time="2011-11-22T00:34:43-03:00"></event>
<message sender="foo@bar.com" time="2011-11-22T00:34:43-03:00" alias="foo"><div><span style="color: #000000; font-family: Helvetica; font-size: 12pt;">hi</span></div></message>
</chat>
推荐答案
我不使用xmllint,但是我认为您的XPath无法正常工作的原因是因为您的doc.xml文件使用的是默认名称空间(
I don't use xmllint, but I think the reason your XPath isn't working is because your doc.xml file is using a default namespace (http://purl.org/net/ulf/ns/0.4-02
).
据我所见,您有2个选择.
From what I can see, you have 2 options.
A..在外壳模式下使用xmllint并使用前缀声明名称空间.然后,您可以在XPath中使用该前缀.
A. Use xmllint in shell mode and declare the namespace with a prefix. You can then use that prefix in your XPath.
xmllint --shell doc.xml
/ > setns x=http://purl.org/net/ulf/ns/0.4-02
/ > xpath /x:chat
B..使用local-name()
匹配元素名称.
B. Use local-name()
to match element names.
xmllint --xpath /*[local-name()='chat']
您可能还希望将namespace-uri()='http://purl.org/net/ulf/ns/0.4-02'
与local-name()
一起使用,因此请确保完全返回您要返回的内容.
You may also want to use namespace-uri()='http://purl.org/net/ulf/ns/0.4-02'
along with local-name()
so you are sure to return exactly what you are intending to return.
这篇关于xmllint无法正确使用xpath查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!