为何Nokogiri::XML::Builder会还原"?如何保留原始内容?
问题描述
示例代码(Ruby):
puts Nokogiri::XML::Builder.new {|b| b.node { b << "foo " bar" }}.to_xml
输出结果:
<?xml version="1.0"?> <node>foo " bar</node>
疑问:使用<<操作符不应保持内容不变吗?如何避免这种自动解析的情况?
解决方案
Nokogiri 的 << 操作符默认会解析传入字符串中的实体引用(比如"),将其转换为对应字符。要保留原始内容,可采用以下两种方法:
使用
text方法并指定:preserve选项
通过text方法传入preserve: true参数,能强制Nokogiri不解析字符串内的实体引用:puts Nokogiri::XML::Builder.new {|b| b.node { b.text("foo " bar", preserve: true) }}.to_xml输出结果:
<?xml version="1.0"?> <node>foo " bar</node>将内容包裹在CDATA块中
CDATA块内的内容会被XML解析器原样保留,不会进行任何解析操作:puts Nokogiri::XML::Builder.new {|b| b.node { b.cdata("foo " bar") }}.to_xml输出结果:
<?xml version="1.0"?> <node><![CDATA[foo " bar]]></node>
内容的提问来源于stack exchange,提问作者Mladen Jablanović
相关产品推荐
相关产品推荐

