Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert text node to XML document containing XML

Tags:

c#

xml

I'm building a XML document dynamically where I create a a text node with CreateTextNode(text) method.

Now in case the text contains XML it will be XML encoded.

For instance:

text = "some <b>bolded</b> text"

How do you insert the text without being XML encoded.

EDIT:

I'm building a XML document with XmlDocument and insert elements and nodes. The final output should not contain CDATA sections or encoded parts.

For instace I want the final output to look like this, where the text comes from a setting:

<root><p>Some <b>bolded</b> text</p></root>
like image 592
Drejc Avatar asked Jun 30 '26 18:06

Drejc


1 Answers

If you want the text to be "some <b>bolded</b> text", then encoding is the right thing - otherwise it isn't (just) a text node. You could CDATA it, but I do not think that is what you mean either.

Do you want the XML contents to be the above text (so that it gets a <b>...</b> element inside it)?


Here's code that adds the content via various methods:

string txt = "some <b>bolded</b> text";
XmlDocument doc = new XmlDocument();
doc.LoadXml("<xml><foo/></xml>");
XmlElement foo = (XmlElement)doc.SelectSingleNode("//foo");

// text: <foo>some &lt;b&gt;bolded&lt;/b&gt; text</foo>
foo.RemoveAll();
foo.InnerText = txt;
Console.WriteLine(foo.OuterXml);

// xml: <foo>some <b>bolded</b> text</foo>
foo.RemoveAll();
foo.InnerXml = txt;
Console.WriteLine(foo.OuterXml);

// CDATA: <foo><![CDATA[some <b>bolded</b> text]]></foo>
foo.RemoveAll();
foo.AppendChild(doc.CreateCDataSection(txt));
Console.WriteLine(foo.OuterXml);
like image 58
Marc Gravell Avatar answered Jul 03 '26 06:07

Marc Gravell