user41871
user41871

Reputation:

Parsing nil XML elements with ActiveResource

I am using ActiveResource to parse the following XML:

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

The output for @deploymentNotifications.platformTest is exactly what I would expect; viz., 'Todd'. The output for the three nil elements, though, looks like this:

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

I'm guessing that ActiveResource doesn't treat xsi:nil as special in any way, but I'm not sure. Ideally what I'd like to end up with (whether using ActiveResource directly or else through a combination of ActiveResource and postprocessing) is a mapping that carries nil input elements to nil Ruby objects:

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

Something along those lines. What is the best way to do this?

I'm completely new to Ruby, so by all means if I need a major course correction, let me know.

Upvotes: 1

Views: 583

Answers (1)

ScottJShea
ScottJShea

Reputation: 7111

This may be available straight from ActiveResource's parser, but if not you can bring in Nokogiri based on this post:

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

From there I did this using your XML from the top of your post:

@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"

You can assign it to the @attributes hash or your object as needed.

Does that help?

Upvotes: 1

Related Questions