Nokogiri 鋸 教程翻译 :修改 HTML/XML文档,Modifying an HTML/XML Document
假设我们面对着以下HTML文档:
@doc = Nokogiri :: HTML :: DocumentFragment .parse <<- EOHTML <body> <h1>Three's Company</h1> <div>A love triangle.</div> </body> EOHTML
|
让我们来修改标题的文本内容:
h1 = @doc .at_css "h1" h1.content = "Snap, Crackle & Pop" @doc .to_html # => "<body> # <h1>Snap, Crackle & Pop</h1> # <div>A love triangle.</div> # # </body>"
|
注意, 当妳使用 #content= 的时候,实体会被正确地转义。妙!
移动节点,最简单的方法就是为它重新赋予一个亲代节点:
h1 = @doc .at_css "h1" div = @doc .at_css "div" h1.parent = div @doc .to_html # => "<body> # # <div>A love triangle.<h1>Three's Company</h1> # </div> # # </body>"
|
但是,妳也可以将它放置在其它节点之后:
div .add_next_sibling (h1) @doc .to_html # => "<body> # # <div>A love triangle.</div> # <h1>Three's Company</h1> # # </body>"
|
h1 .name = 'h2' h1[ 'class' ] = 'show-title' @doc .to_html # => "<body> # <h2 class=\"show-title\">Three's Company</h2> # <div>A love triangle.</div> # # </body>"
|
h3 = Nokogiri :: XML :: Node .new "h3" , @doc h3.content = "1977 - 1984" h1.add_next_sibling(h3) @doc .to_html # => "<body> # <h1>Three's Company</h1> # <h3>1977 - 1984</h3> # <div>A love triangle.</div> # # </body>"
|
如果妳想在某个Nodeset 中的每个节点外面包装一层HTML的话,则,可参照以下示例:
nodes = @doc .css "h1,div" nodes.wrap("<div class='container'></div>") @doc .to_html # => "<body> # <div class=\"container\"><h1>Three's Company</h1></div> # <div class=\"container\"><div>A love triangle.</div></div> # # </body>"
|
如果 妳想要添加一条处理指令 ( 即, “PI节点”) ,例如一个 xml-stylesheet声明 ,那么,妳应当首先使用 Nokogiri::XML::ProcessingInstruction.new 来创建该节点,然后,将它添加到文档中,作为根节点的前导邻居节点:
doc = Nokogiri :: XML "<root>foo</root>" doc.to_xml # => "<?xml version=\"1.0\"?> # <root>foo</root> # " pi = Nokogiri :: XML :: ProcessingInstruction .new(doc, "xml-stylesheet", 'type="text/xsl" href="foo.xsl"') doc.root.add_previous_sibling pi doc.to_xml # => "<?xml version=\"1.0\"?> # <?xml-stylesheet type=\"text/xsl\" href=\"foo.xsl\"?> # <root>foo</root> # "
|
未知美人
秦岚
Your opinions
HxLauncher: Launch Android applications by voice commands