xmllint 无法使用 xpath 正确查询 [英] xmllint failing to properly query with xpath

查看:37
本文介绍了xmllint 无法使用 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 文件使用了默认命名空间(http://purl.org/net/ulf/ns/0.4-02).

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).

据我所知,您有两个选择.

From what I can see, you have 2 options.

A. 在 shell 模式下使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆