Nokogiri:使用"搜索节点:"

时间:2017-12-04 13:18:03

标签: ruby-on-rails nokogiri

我有一个简单的XML结构:

<?xml version="1.0" encoding="utf-8"?>
<response xmlns:msg="..." xmlns:ld="...">
  <msg:testResultBatch providerId="12345" testName="Hello Labs">
    .
    .
    .
  </msg:testResultBatch>
</response>

当我将其传递给Nokogiri.XML时:

req = Nokogiri.XML('
    <?xml version="1.0" encoding="utf-8"?>
    <response xmlns:msg="..." xmlns:ld="...">
      <msg:testResultBatch providerId="12345" testName="Hello Labs">
        .
        .
        .
      </msg:testResultBatch>
    </response>
')

我无法使用&#34;:&#34;搜索节点。所以,

req.search("response") # works

但是,

req.search("msg:testResultBatch") # doesn't works

并给我[]

1 个答案:

答案 0 :(得分:1)

通过使用xpath和'//msg:testResultBatch',您可以获得msg:testResultBatch

require 'nokogiri'

req = Nokogiri.XML('
<?xml version="1.0" encoding="utf-8"?>
<response xmlns:msg="..." xmlns:ld="...">
  <msg:testResultBatch providerId="12345" testName="Hello Labs">
  </msg:testResultBatch>
</response>
')
p req.xpath('//msg:testResultBatch').first.name # "testResultBatch"