How can i put a string with an ampersand in an xml file with Nokogiri?

余生长醉 提交于 2019-12-05 19:19:28

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 <!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)

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>

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]]>'

Then you get this XML:

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

and that doesn't even have a CDATA node.

Did you try to replace the ampersand with its xml/html character code ? It should be working.

The code for the ampersand is: &amp;

Click here for more information about character codes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!