Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何使用Nokogiri获取XML的第一级子级_Ruby_Xml_Xpath_Nokogiri - Fatal编程技术网

Ruby 如何使用Nokogiri获取XML的第一级子级

Ruby 如何使用Nokogiri获取XML的第一级子级,ruby,xml,xpath,nokogiri,Ruby,Xml,Xpath,Nokogiri,我正在尝试使用Nokogiri解析POM文件,并希望获得第一级子节点 我的POM文件如下所示: <project xmlns="some.maven.link"> <parent> <groupId>parent.jar</groupId> <artifactId>parent-jar</artifactId> </parent> <groupId

我正在尝试使用Nokogiri解析POM文件,并希望获得第一级子节点

我的POM文件如下所示:

<project xmlns="some.maven.link">
   <parent>
     <groupId>parent.jar</groupId>
     <artifactId>parent-jar</artifactId>  
   </parent>         
   <groupId>child.jar</groupId>
   <artifactId>child-jar</artifactId>
 </project>

我可以访问第二个元素,但那只是一个黑客

您的XML示例似乎不正确。简化它:

require 'nokogiri'

doc = Nokogiri::XML(<<EOT)
<project>
  <parent>
    <groupId>parent.jar</groupId>
    <artifactId>parent-jar</artifactId>  
  </parent>         
  <groupId>child.jar</groupId>
  <artifactId>child-jar</artifactId>
</project>
EOT

doc.at('project > artifactId').text # => "child-jar"
我建议学习
search
xpath
css
和它们的
at*
表亲之间的区别,它们都记录在“”和文档中

在上面的示例中,我删除了XML名称空间信息以简化事情。XML名称空间很有用,但也很烦人,在您的示例XML中,由于没有提供有效的URL而破坏了它。用以下方法修复该示例:

<project xmlns="http://www.w3.org/1999/xhtml">
或:

我更喜欢并推荐第一种,因为它可读性更强,噪音更小。 Nokogiri在选择器中实现CSS有助于简化大多数选择器。在文档中传入收集的名称空间简化了搜索,无论您使用的是CSS还是XPath

这些措施也起作用:

doc.at('/xmlns:project/xmlns:artifactId').text # => "child-jar"
doc.at('/foo:project/foo:artifactId', {'foo' => "http://www.w3.org/1999/xhtml"}).text # => "child-jar"
请注意,第二个名称空间使用重命名的名称空间,如果您正在处理文档中的冗余
xmlns
声明,并且需要区分它们,则此名称空间非常有用


Nokogiri的“”教程很有帮助。

虽然我没有测试ruby代码的工具,但是XPath应该只返回“child jar”:。问题是名称空间。它没有在选择器中被引用,所以Nokogiri/libXML2不知道在哪里查找。
<project xmlns="http://www.w3.org/1999/xhtml">
namespaces = doc.collect_namespaces  # => {"xmlns"=>"http://www.w3.org/1999/xhtml"}
doc.at('project > artifactId', namespaces).text # => "child-jar"
doc.at('xmlns|project > xmlns|artifactId').text # => "child-jar"
doc.at('/xmlns:project/xmlns:artifactId').text # => "child-jar"
doc.at('/foo:project/foo:artifactId', {'foo' => "http://www.w3.org/1999/xhtml"}).text # => "child-jar"