【问题标题】:Parsing nil XML elements with ActiveResource使用 ActiveResource 解析 nil XML 元素
【发布时间】:2013-01-15 09:26:39
【问题描述】:

我正在使用 ActiveResource 来解析以下 XML:

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

@deploymentNotifications.platformTest 的输出正是我所期望的;即,“托德”。但是,三个 nil 元素的输出如下所示:

"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 输入元素携带到 nil Ruby 对象的映射:

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

类似的东西。最好的方法是什么?

我对 Ruby 完全陌生,所以如果我需要大修课程,一定要告诉我。

【问题讨论】:

    标签: ruby-on-rails ruby xml activeresource xml-nil


    【解决方案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 哈希或您的对象。

    这有帮助吗?

    【讨论】:

    • 嗨,斯科特,感谢您发送此信息。我即将起飞一个星期,但当我回来时,我会试一试。
    猜你喜欢
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2013-07-10
    • 2011-06-11
    相关资源
    最近更新 更多