Question

I have an xml document and I want to add child elements under the element with the name 'InitgPty' and I'm attempting to do so as follows:

filename = "#{payment.updated_at.strftime("%Y%m%d")}.xml"
file_contents = File.read("#{filename}")

doc = Nokogiri::XML(file_contents)

initgpty = doc.at_xpath("//InitgPty")
first_id_tag = Nokogiri::XML::Node.new "Id", doc
initgpty.add_next_sibling(first_id_tag)

The problem is that

initgpty = doc.at_xpath("//InitgPty")

returns nil so I'm getting a NoMethodError on .add_next_sibling. This is my first time working with both XML and nokogiri but, to me, the XML generated by

doc = Nokogiri::XML(file_contents)

looks very strange. Here's a snippet from what that line outputs in the rails console:

#<Nokogiri::XML::Element:0x58d9582 name="InitgPty" namespace=#<Nokogiri::XML::Namespace:0x58ce1be href="urn:iso:std:iso:20022:tech:xsd:pain.008.003.02"> children=[#<Nokogiri::XML::Text:0x58d92d0 "\n        ">, #<Nokogiri::XML::Element:0x58d9212 name="Nm" namespace=#<Nokogiri::XML::Namespace:0x58ce1be href="urn:iso:std:iso:20022:tech:xsd:pain.008.003.02"> children=[#<Nokogiri::XML::Text:0x58d8e84 "B8S Chatter Creators">]>, #<Nokogiri::XML::Text:0x58d8d12 "\n      ">]>

Is this correct and the NoMethodError is being caused by something else? Any help at all on this matter would be greatly appreciated.

Was it helpful?

Solution

Try to use CSS selectors. This also works for XML-documents:

doc.css('InitgPty').first
#should return the first element named InitgPty
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top