I'm starting with Nokogiri and have an important doubt about how to
add a child containing attributes, text and subtrees on a parent node
of a parsed XML document.
This is: I have the following XML document parsed in @document:
-------------------------
<?xml version='1.0' encoding='UTF-8'?>
<cp:ruleset xmlns:pr="urn:ietf:params:xml:ns:pres-rules"
xmlns:cp="urn:ietf:params:xml:ns:common-policy">
<cp:rule id="pres_blacklist">
<cp:identity>
<cp:one id="sip:b...@domain.net">Bob</cp:one>
</cp:identity>
</cp:rule>
</cp:ruleset>
-------------------------
I just want to add a new child into <cp:identity> node, something as:
<cp:one id="sip:al...@domain.net">Alice</cp:one>
So I do:
-----------------------------------
ns = { "xmlns:pr" => "urn:ietf:params:xml:ns:pres-rules", "xmlns:cp"
=> "urn:ietf:params:xml:ns:common-policy" }
parent_node = @document.xpath('/cp:ruleset/cp:rule[@id="pres_blacklist"]/cp:identity',
ns)[0]
new_node = Nokogiri::XML::Node.new('<cp:one
id="sip:al...@domain.net">Alice</cp:one>', @document)
parent_node.add_child(new_node)
-----------------------------------
The result is really wrong as I get:
<cp:identity>
<cp:one id="sip:b...@domain.net">Bob</cp:one>
<cp:<cp:one id="sip:al...@domain.net">Alice</cp:one>/>
</cp:identity>
So, what is the proper way to do waht I need? perhaps I must create a
simple node 'cp:one id="sip:al...@domain.net"' and later add a text
value to it?
What about if I want to insert a new child containing a XML subtree?
Thanks for any suggestion.
--
Iñaki Baz Castillo
<i...@aliax.net>
Ok, I can get it by following these steps:
> -----------------------------------
> ns = { "xmlns:pr" => "urn:ietf:params:xml:ns:pres-rules", "xmlns:cp"
> => "urn:ietf:params:xml:ns:common-policy" }
>
> parent_node = @document.xpath('/cp:ruleset/cp:rule[@id="pres_blacklist"]/cp:identity',
> ns)[0]
>
> new_node = Nokogiri::XML::Node.new("one", @document)
> new_node[id] = "sip:alice@domain-net"
> new_node.content = "Alice"
>
> parent_node.add_child(new_node)
> -----------------------------------
Is it the only way? cannot I add the entire node (containing
attributes, text content and optional sub-childs) directly?
Thanks.