Thang Le Sy Thang Le Sy - 7 months ago 26
Ruby Question

Modifying an XML document with Nokogiri

I am using Nokogiri to modify the content of an XML file:

<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="png" ContentType="image/png"/>
...
</Types>


I need add
Default
children to
Types
as follows:

<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="png" ContentType="image/png"/>
<Default Extension="jpg" ContentType="image/jpeg"/>
...
</Types>


I tried:

child_node = Nokogiri::XML::Node.new "Default", @doc
@doc.xpath('//Types/Default').first.add_next_sibling(child_node)


#but @doc.xpath('//Types/Default').first #=> nil


How can I add a child node to
Types
?

Answer

Using an XPath query against XML with a default namespace has been asked many times here in StackOverflow. In fact, I just posted an answer to a C# question on the same topic a couple hours ago.

I don't know Ruby in particular, but commonly, to select an element in a default namespace using XPath, you need to map a prefix to the default namespace URI and use that prefix in your XPath, something like:

child_node = Nokogiri::XML::Node.new "Default", @doc
result = @doc.xpath('/d:Types/d:Default', 'd' => 'http://schemas.openxmlformats.org/package/2006/content-types').first