jquery set xml cdata

余生颓废 提交于 2020-01-04 05:19:10

问题


I have a problem setting a cdata node with jquery. Getting cdata is easily done with the .text() function, but if I use .text('jquery > handy') it doesn't create a cdata node.

This is my procecure: I get form data in xml to load in a form something like this:

<formdata>
  <field id="title"><![CDATA[Some title]]></field>
  <field id="description"><![CDATA[Some description]]></field>
</formdata>

I use cdata nodes because a field can contain all kinds of special chars. Then I load the data in the form by getting the node content with .text()

If the user posts the form, I update the xml and convert it to a sting to post it to the server. I know I could just post the fields, but I have some good reasons to put it in an xml document. Everything works very well, but not if the user does some input with special characters. This is how i set the value of the node (in this example the "descriptioon node")

domdoc.find('field[id="description"]').text($("#description").val());

So the node used to be cdata, but the .text() function removes that. I alo tried this:

domdoc.find('field[id="description"]').text('<![CDATA[' + $("#description").val() + ']]>');

This also doesn't work because .text() changes < to &gt;

does anyone has a solution? My inspiration is gone.....

Thanks, Simon


回答1:


Just set text, without adding <![CDATA[. CDATA is just one of the ways to escape text in XML, but since jQuery escapes for you, you don't need to use another method. &lt; is just as good as <![CDATA[<]]>. For XML applications they're identical.




回答2:


Simple solution. Create a CData Section Node and Append it to your XML. I struggled with the JQuery .text() with no luck. This worked fantastic.

            var cDataSection = self.xmlDocument.createCDATASection(text);
            $(element).empty();
            $(element).append(cDataSection);


来源:https://stackoverflow.com/questions/4246923/jquery-set-xml-cdata

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