[英]Nokogiri parsing Rackspace return using XPath in Rails
I'm using Nokogiri to parse a return from the Rackspace API so I'm using their sample code to 我正在使用Nokogiri解析来自Rackspace API的返回值,因此我正在使用其示例代码来
response = server.get '/customers/'+@user.customer_id.to_s+'/domains/', server.xml_format
doc = Nokogiri::XML::parse response.body
puts "xpath values"
doc.xpath("//name").each do |node|
puts
node.text
end
As my code to use Nokogiri to return the nodelist of nodes of the element 作为我使用Nokogiri返回元素节点节点列表的代码
for some reason I seem to have missed something obvious and I just for the life of me cannot get it to parse the list of nodes and return them to me, is there something simple I can do to fix to have it return the list of nodes? 由于某种原因,我似乎错过了一些显而易见的事情,而我一生都无法获取它来解析节点列表并将其返回给我,我可以做些简单的事情来修复它使其返回节点列表吗? ?
Here's an example of the XML I'm trying to parse: 这是我要解析的XML的示例:
<domainList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:xml:domainList">
<offset>0</offset>
<size>50</size>
<total>4</total>
<domains>
<domain>
<name>domain1.com</name>
<accountNumber>xxxxxxx</accountNumber>
<serviceType>exchange</serviceType>
</domain>
<domain>
<name>domain2.com</name>
<accountNumber>xxxxxxx</accountNumber>
<serviceType>exchange</serviceType>
</domain>
<domain>
<name>domain3.com</name>
<accountNumber>xxxxxxx</accountNumber>
<serviceType>exchange</serviceType>
</domain>
</domains>
</domainList>
Cheers 干杯
The issue seems to be that you have to tell Nokogiri about their namespace. 问题似乎是您必须告诉Nokogiri他们的名称空间。
If you remove xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:xml:domainList"
from your domainLists tag you'd see your query work. 如果您删除
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:xml:domainList"
您可以通过domainLists标记中的xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:xml:domainList"
来查看查询。
Otherwise you need to tell Nokogiri about that namespace. 否则,您需要向Nokogiri告知该名称空间。
doc.xpath("//blarg:name", {'blarg' => 'urn:xml:domainList'}).each do |name|
puts name.text
end
Nokogiri xpath takes a second argument which is a hash of namespaces. Nokogiri xpath使用第二个参数,它是名称空间的哈希。 The xml you have defines a general namespace but doesn't give it a tag.
您拥有的xml定义了通用名称空间,但未为其提供标签。 I don't know if there is a way for nokogiri to just find this, so instead on your searches just give your search an arbitrary tag and associate the namespace path with that tag.
我不知道nokogiri是否有办法找到它,所以在您的搜索中,只是给您的搜索一个任意标记,然后将名称空间路径与此标记关联。 You can put whatever text you want instead of blarg, it was just for the example.
您可以输入所需的任何文本,而不是blarg,仅用于示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.