2012-02-14 71 views
1

我使用的ActiveResource来解析下面的XML:解析用的ActiveResource零XML元素

<deploymentNotifications> 
    <platformTest>Todd</platformTest> 
    <domainTest xsi:nil="true"/> 
    <systemTest xsi:nil="true"/> 
    <production xsi:nil="true"/> 
</deploymentNotifications> 

@deploymentNotifications.platformTest输出正是我所期望的;即'托德'。三个零元素的输出,虽然看起来是这样的:

"domainTest"=> 
    #<Application::DeploymentNotifications::DomainTest:0x007f7f8df7a198 
     @attributes={ 
      "xmlns:xsi"=>"http://www.w3.org/2001/XMLSchema-instance", 
      "xsi:nil"=>"true"}, 
     @prefix_options={}, 
     @persisted=false> 

我猜的ActiveResource不把xsi:nil特殊以任何方式,但我不知道。理想我想与落得什么(无论是直接或其他使用的ActiveResource通过的ActiveResource和后处理的组合)是携带零输入元素为nil Ruby对象的映射:

#<Application::DeploymentNotifications:0x007f7f8ec6a290 
    @attributes={ 
     "platformTest"=>"Todd", 
     "domainTest"=>nil, 
     "systemTest"=>nil, 
     "production"=>nil}, 
    @prefix_options={}, 
    @persisted=false> 

沿这些行的东西。做这个的最好方式是什么?

我对Ruby完全不熟悉,所以无论如何,如果我需要重大修正,请告诉我。

回答

1

这可能是可直接从的ActiveResource的解析器,但如果没有,你可以根据this post中引入nokogiri带来:

ActiveSupport::XmlMini.backend = 'Nokogiri' 
ActiveSupport::XmlMini.backend # => ActiveSupport::XmlMini_Nokogiri 
# it will now use Nokogiri 

从那里我这样做是使用你从你的后上方XML:

@doc = Nokogiri::XML(File.open("willie.xml")) # willie.xml is your XML 
@domain_test_Value = @doc.xpath("//domainTest").attribute("nil").value 
puts @domain_test_Value 
# "true" 

您可以根据需要将它分配给@attributes散列或对象。

这有帮助吗?

+0

嘿斯科特,谢谢你发送这个。我即将起飞一周,但当我回来时,我会试一试。 – 2012-03-17 03:46:17