【问题标题】:Parsing XML file with nokogiri使用 nokogiri 解析 XML 文件
【发布时间】:2013-07-26 17:47:44
【问题描述】:

我有以下 xml 文件:

<?xml version='1.0' encoding='UTF-8'?>
<sparql xmlns='http://www.w3.org/2005/sparql-results#'>
        <head>
                <variable name='s'/>
        </head>
        <results>
                <result>
                        <binding name='s'>
                                <uri>http://data.open.ac.uk/podcast/c9ddc42f6e1db95f59c83312d62da0ee</uri>
                        </binding>
                </result>
                <result>
                        <binding name='s'>
                                <uri>http://data.open.ac.uk/podcast/18873effb6c38ed83a7522ffb7c61c1b</uri>
                        </binding>
                </result>
        </results>
</sparql>

我想从文档中获取 uri。我尝试了这些命令:

doc = Nokogiri::XML(File.open("file.xml"))
doc.xpath("//uri")

但它返回 nil。

但是,如果我将文件修改为:

<results>
                    <result>
                            <binding name='s'>
                                    <uri>http://data.open.ac.uk/podcast/c9ddc42f6e1db95f59c83312d62da0ee</uri>
                            </binding>
                    </result>
                    <result>
                            <binding name='s'>
                                    <uri>http://data.open.ac.uk/podcast/18873effb6c38ed83a7522ffb7c61c1b</uri>
                            </binding>
                    </result>
            </results>

以上命令正确返回了 uri。

【问题讨论】:

    标签: ruby xpath nokogiri


    【解决方案1】:

    您需要指定要选择的元素的命名空间。在第一个文档中,这是http://www.w3.org/2005/sparql-results#,继承自根节点。在第二个文档中它有效,因为您通过删除该根节点删除了命名空间声明。

    好消息是因为你的命名空间是在根节点中定义的,Nokogiri 会自动为你注册它,你应该可以选择&lt;uri&gt; 元素

    doc.xpath("//xmlns:uri")
    

    【讨论】:

    • 或者,使用css() 方法(忽略命名空间),即doc.css('uri') 或使用doc.remove_namespaces! 的核破坏性方法,然后您的原始代码将起作用。
    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 2014-07-05
    • 1970-01-01
    相关资源
    最近更新 更多