Note that there are some explanatory texts on larger screens.

plurals
  1. PONokogiri: controlling element prefix for new child elments
    primarykey
    data
    text
    <p>I have an xml document like this:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;foo:root xmlns:foo="http://abc.com#" xmlns:bar="http://def.com" xmlns:ex="http://ex.com"&gt; &lt;foo:element foo:attribute="attribute_value"&gt; &lt;bar:otherElement foo:otherAttribute="otherAttributeValue"/&gt; &lt;/foo:element&gt; &lt;/foo:root&gt; </code></pre> <p>I need to add child elements to the element so that it looks like this:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;foo:root xmlns:foo="http://abc.com#" xmlns:bar="http://def.com" xmlns:ex="http://ex.com"&gt; &lt;foo:element foo:attribute="attribute_value"&gt; &lt;bar:otherElement foo:otherAttribute="otherAttributeValue"/&gt; &lt;bar:otherElement foo:otherAttribute="newAttributeValue"/&gt; &lt;ex:yetAnotherElement foo:otherAttribute="yetANewAttributeValue"/&gt; &lt;/foo:element&gt; &lt;/foo:root&gt; </code></pre> <p>I can add elements in the correct location using the following:</p> <pre><code>require 'rubygems' require 'nokogiri' doc = Nokogiri::XML::Document.parse(File.open("myfile.xml")) el = doc.at_xpath('//foo:element') newEl = Nokogiri::XML::Node.new("otherElement", doc) newEl["foo:otherAttribute"] = "newAttributeValue" el.add_child(newEl) newEl = Nokogiri::XML::Node.new("yetAnotherElement", doc) newEl["foo:otherAttribute"] = "yetANewAttributeValue" el.add_child(newEl) </code></pre> <p>However the prefix of the new elements is always "foo":</p> <pre><code>&lt;foo:root xmlns:foo="http://abc.com#" xmlns:bar="http://def.com" xmlns:ex="http://ex.com"&gt; &lt;foo:element foo:attribute="attribute_value"&gt; &lt;bar:otherElement foo:otherAttribute="otherAttributeValue" /&gt; &lt;foo:otherElement foo:otherAttribute="newAttributeValue" /&gt; &lt;foo:yetAnotherElement foo:otherAttribute="yetANewAttributeValue" /&gt; &lt;/foo:element&gt; &lt;/foo:root&gt; </code></pre> <p>How can I set the prefix on the element name for these new child elements? Thanks, Eoghan</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload