Reputation: 199
I wanted to know if it's possible (and how of course) to get the position of a tag compare to the content of the parent tag. For example:
Case 1: <a>Hello<br/></a>
Case 2: <a><br/>Hello</a>
Here i want to know if br is place before or after "br" tag
EDIT: My real aim is actually to convert:
<a>Hello</a>
<a>World!<br/></a>
<a><br/>I</a>
<a>love</a>
<a>Rails.</a>
into
Hello World!
I love Rails.
But my current code is convert it like that:
Hello World!
I
love Rails
Because i'm looking for each "a" tag and if br exist i create a new line.
Upvotes: 1
Views: 415
Reputation: 4847
Try to use children
when get a
. Something like this:
str = '<doc><a>Hello</a>
<a>World!<br/></a>
<a><br/>I</a>
<a>love</a>
<a>Rails.</a></doc>'
doc = Nokogiri::XML.parse(str)
out = ""
doc.css('doc a').each do |block|
block.children.each do |node|
if node.element?
out += "<a></" + node.name + "></a>\n"
else
out += "<a>" + node.text + "</a>\n"
end
end
end
puts out
Output is:
<a>Hello</a>
<a>World!</a>
<a></br></a>
<a></br></a>
<a>I</a>
<a>love</a>
<a>Rails.</a>
You should cope with two br's in this case though...
Upvotes: 1