如何使用Nokogiri将带有&符号的字符串放入xml文件中? [英] How can i put a string with an ampersand in an xml file with Nokogiri?

查看:70
本文介绍了如何使用Nokogiri将带有&符号的字符串放入xml文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在XML文件中包含图像的URL,并且URL查询字符串中的&符被剥离:

I'm trying to include a URL to an image in an XML file, and the ampersands in the URL query string are getting stripped out:

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的帮助下写出。但不是单个元素,而是一次全部插入。

bgdoc is getting written out with the help of Builder later on. But not the individual elements, it's getting inserted all at once. That makes it a different case than a similar question posted on SO.

推荐答案

您应该使用 create_cdata 来创建CDATA节点并然后 add_child 将其添加到文档中,只需为 content 分配一个字符串,就会留下& lt;!CDATA ... 在XML中,这不是很有用。

You should be using create_cdata to create a CDATA node and then add_child to add it to the document, just assigning a string to content will leave you with &lt;!CDATA... in your XML and that's not very useful.

一个简短的示例应说明该过程:

A short example should illustrate the process:

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 得到一些喜欢这个:

Then, if you bgdoc.to_xml you'll get something like this:

<?xml version="1.0"?>
<Master>
    <Image><![CDATA[/where?is=pan&cakes=house]]></Image>
    <Image/>
</Master>

我认为这就是您想要的结果。但是,如果仅将字符串分配给 content

I think that's the sort of result you're looking for. However, if you just assign a string to content:

bgdoc.xpath('//Image').first.content = '<![CDATA[/where?is=pan&cakes=house]]>'

然后您将获得以下XML:

Then you get this XML:

<?xml version="1.0"?>
<Master>
    <Image>&lt;![CDATA[/where?is=pan&amp;cakes=house]]&gt;</Image>
    <Image/>
</Master>

甚至没有CDATA节点。

and that doesn't even have a CDATA node.

这篇关于如何使用Nokogiri将带有&符号的字符串放入xml文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆