Combining sibling nodes.

3 views
Skip to first unread message

Wayne Brissette

unread,
Jun 17, 2020, 5:27:04 PM6/17/20
to nokogiri-talk
I have a situation where I have this:

<example>
    <codeblock>
STCALIB[25]   = 1'b0; // reference provided
    </codeblock>
    <codeblock>
STCALIB[24]   = 1'b1; // skew
    </codeblock>
    <codeblock>
STCALIB[23:0] = (32768 x 10mS) -1
    </codeblock>
</example>

What I need to do is combine the childnodes so I end up with this:

<example>
    <codeblock>
STCALIB[25]   = 1'b0; // reference provided
STCALIB[24]   = 1'b1; // skew
STCALIB[23:0] = (32768 x 10mS) -1
    </codeblock>
</example

The closest I can come is finding each codeblock element, getting the
next element, comparing the names of the two nodes, if they match
(<codeblock/><codeblock/>) then take the content of both, combining
those, deleting the second codeblock element, then replacing the initial
codeblock element with the combined text.

There has to be a better way to do this. Anybody know how to combine
siblings nodes that have the same node name?

Thanks,
Wayne

Mike Dalessio

unread,
Jun 18, 2020, 8:47:42 AM6/18/20
to nokogiri-talk
Hi Wayne,

Here's what I tried:

#! /usr/bin/env ruby

require "nokogiri"

xml = <<-EOX

<example>
     <codeblock>
STCALIB[25]   = 1'b0; // reference provided
     </codeblock>
     <codeblock>
STCALIB[24]   = 1'b1; // skew
     </codeblock>
     <codeblock>
STCALIB[23:0] = (32768 x 10mS) -1
     </codeblock>
</example>
EOX

doc = Nokogiri::XML(xml)

parent_node = doc.at_css("example")
children_nodes = parent_node.xpath("./codeblock")

# remove children, create new child
new_node_content = children_nodes.map { |node| node.text }.join
children_nodes.each { |node| node.unlink }
parent_node.add_child("<codeblock>#{new_node_content}</codeblock>")

puts doc.to_xml

which emits

<?xml version="1.0"?>

<example>
     
     
     
<codeblock>
STCALIB[25]   = 1'b0; // reference provided
     
STCALIB[24]   = 1'b1; // skew
     
STCALIB[23:0] = (32768 x 10mS) -1
     </codeblock></example>

and I think you could pretty easily clean up the whitespace if you wanted to. Does that meet your needs?


--
You received this message because you are subscribed to the Google Groups "nokogiri-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nokogiri-tal...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/nokogiri-talk/60efcdb4-73f6-70a0-1cfa-0fadb8867394%40att.net.

Wayne Brissette

unread,
Jun 18, 2020, 10:37:00 AM6/18/20
to nokogi...@googlegroups.com, Mike Dalessio
As always, thank you! This does in fact fix my problem.

-Wayne


Reply all
Reply to author
Forward
0 new messages