nokogiri: xml to html
I just want to do some straight conversion (almost just search and replace) but I'm having trouble just getting things to sit in place - I'm ending up with links out of place and duplicated content. I'm sure I'm doing something silly with my attempts at traversing the xml : )
I'm trying with:
builder = Nokogiri::HTML::Builder.new do |doc|
doc.html {
doc.body {
doc.div.wrapper! {
doc.h1 "Short"
xm.css('paragraph').each do |para|
doc.h3.para(:id => para['number']) { doc.text para['number'] }
doc.p.narrativeparagraph {
xm.css('paragraph inner-section').each do |section|
doc.span.innersection { doc.text section.content
xm.css('inner-section xref').each do |xref|
doc.a(:href => "#" + xref['number']) { doc.text xref['number'] }
end
xm.css('paragraph inner-text').each do |innertext|
doc.span.innertext { doc.text innertext.content }
end
} end #inner-section
}
end#end paragraph
}#end wrapper
}#end body
}#end html
end#end builder
on:
<?xml version="1.0"?>
<looseleaf>
<paragraph number="1">
<inner-section> blah one blah <xref number="link1location"></xref>
<inner-text> blah two blah blah </inner-text>
blah three
</inner-section>
</paragraph>
<paragraph number="2">
<inner-section> blah four blah <xref number="link2location"></xref>
<inner-text>blah five blah blah </inner-text>
blah six
</inner-section>
</paragraph>
</looseleaf>
to create:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC- html40/loose.dtd">
<html>
<body>
<div id="wrapper">
<h1>Short</h1>
<h3 class="para" id="1">1</h3>
<p class="narrativeparagraph">
<span class="innersection"> blah one blah <a href="#link1location">link1location</a>
<span class="innertext"> blah two blah blah </span>
blah three</span>
</p>
<h3 class="para" id="2">2</h3>
<p class="narrativeparagraph">
<span class="innersection"> blah four blah <a ref="#link2location">link2location</a>
<span class="innertext">blah five blah blah </开发者_JAVA百科span>
blah six</span></p>
I've been trying all sorts of things to try to get this to work, the basic html structure comes out okay, but the children of the paragraphs are a mess - any help would be very much appreciated. Regards, Ritchie
There are many ways to do this, but if you insist on the Builder way, I would make a function that translates <paragraph>
to <p>
.
builder = Nokogiri::HTML::Builder.new do |doc|
doc.html {
doc.body {
doc.div.wrapper! {
doc.h1 "Short"
xm.css('paragraph').each do |para|
doc << translate_paragraph para.dup
end #para
}#end body
}#end html
end#end builder
def translate_paragraph(p)
# Change '<paragraph>' to '<p>'
p.name = 'p'
# Change '<innersection>' to '<span class='innersection'>'
p.css('innersection').each { |tag|
tag.name = 'span'
tag['class'] = 'innersection'
}
# ...
end
Not perfect, but it works with Builder.
I would also consider XSLT, or traversing the HTML tree recursively and building from there.
精彩评论