我试图在 XML 文件中包含图像的 URL,并且 URL 查询字符串中的 & 符号被删除:
bgdoc.xpath('//Master').each do |elem|
part = elem.xpath('Part').inner_text
image = imagehash[part]
image = "" if image.blank?
elem.xpath('Image').first.content = "<![CDATA[#{image}]]>"
puts elem.xpath('Image').first.content
end
bgdoc 稍后会在 Builder 的帮助下编写出来。但不是单个元素,它是一次性插入的。这使得它与 SO 上发布的类似问题不同。
你应该使用create_cdata http://nokogiri.org/Nokogiri/XML/Document.html#method-i-create_cdata创建一个 CDATA 节点,然后add_child http://nokogiri.org/Nokogiri/XML/Node.html#method-i-add_child要将其添加到文档中,只需分配一个字符串即可content
会给你留下<!CDATA...
在你的 XML 中,这不是很有用。
一个简短的例子应该可以说明这个过程:
xml = '<Master><Image></Image><Image></Image></Master>'
bgdoc = Nokogiri::XML(xml)
cdata = bgdoc.create_cdata('/where?is=pan&cakes=house')
bgdoc.xpath('//Image').first.add_child(cdata)
那么,如果你bgdoc.to_xml
你会得到这样的东西:
<?xml version="1.0"?>
<Master>
<Image><![CDATA[/where?is=pan&cakes=house]]></Image>
<Image/>
</Master>
我认为这就是您正在寻找的结果。但是,如果您只是将一个字符串分配给content
:
bgdoc.xpath('//Image').first.content = '<![CDATA[/where?is=pan&cakes=house]]>'
然后你会得到这个 XML:
<?xml version="1.0"?>
<Master>
<Image><![CDATA[/where?is=pan&cakes=house]]></Image>
<Image/>
</Master>
而且它甚至没有 CDATA 节点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)