Ruby - 使用nokogiri从XML中提取值

时间:2014-05-26 13:56:22

标签: ruby xml nokogiri

这是我的XML:

<Group ID="1" ParentGroupID="5" targetHostname="" Name="127.0.0.1[192.168.0.8]:80 | 81 | 80" LoadBalancerMaxConnections="0" State="1" ProtocolType="TCP" Description="HttpProxy" ProtocolName="HttpProxy">
  <Instance ID="1" Type="CrossProtocol.CrossProtocolHost" NoDelay="False" KeepAlive="False" LocalIP="0.0.0.0" LocalPort="80" ServiceID="-1" MaxConnections="0" RemoteIP="127.0.0.1" RemotePort="80" CallBackPort="81" Description="HttpProxy" DesignatedIP="1.1.1.1" ProtocolName="HttpProxy">
    <IPAddressRestriction Name="Restrict or grant access to services based on IP addresses" Type="0" Description="">
    </IPAddressRestriction>
  </Instance>
  <Instance ID="2" Type="CrossProtocol.CrossProtocolHost" LocalIP="0.0.0.0" LocalPort="81" ServiceID="0" MaxConnections="0" Description="HttpProxy">
    <IPAddressRestriction Name="IPAddress Restriction" Type="0" Description="Restrict or grant access to services based on IP addresses">
    </IPAddressRestriction>
  </Instance>
</Group>

我想从XML中获取RemotePort的值以用作变量,我尝试使用:

doc.xpath("//Instance/RemotePort")

但我得到的回应是:

doc.xpath("//Instance/RemotePort")
=> []

我做错了什么?

1 个答案:

答案 0 :(得分:3)

doc.xpath('//Instance/@RemotePort')
# => [#<Nokogiri::XML::Attr:0x11615d8 name="RemotePort" value="80">]

doc.xpath('//Instance/@RemotePort').map(&:value)
# => ["80"]