Reputation: 9546
I'm trying to add the ASCII carriage return
to the end of a string in an XmlNode's InnerText
like this:
XmlNode spanNode = doc.CreateElement("span");
spanNode.InnerText = "carriage return here: ";
rootNode.AppendChild(spanNode);
But this ends up escaping the string, so that it appears in rootNode
's OuterXml like this:
carriage return here: 
How do I add this text if I actually want the unescaped carriage return?
EDIT: if it makes a difference, this is for text that will be displayed in a PDF annotation. I'm changing the value of the RC
key that defines the rich text--removing some existing <span>
elements with this carriage return and adding new ones that have an identical carriage return.
Here's what I want to end up with:
<root>
<span>carriage return here: </span>
</root>
Upvotes: 0
Views: 424
Reputation: 9546
Solved this really easily by setting InnerXml
instead of InnerText
:
XmlNode spanNode = doc.CreateElement("span");
spanNode.InnerXml = "carriage return here: ";
rootNode.AppendChild(spanNode);
EDIT: this does not actually create the desired text. Trying to find a different approach.
Upvotes: 0
Reputation: 4668
You want to include a CDATA section. Otherwise the parser will interpret carriage returns as unneeded whitespace. The "duplicate" link i referred to (in comments above) in alludes to this, but MS has more info. You don't need to encode the carriage returns as long as they're in the CDATA section.
https://msdn.microsoft.com/en-us/library/system.xml.xmldocument.createcdatasection(v=vs.110).aspx
For reference's sake , I've modified Microsoft's example. Take note of the \r \n characters.
using System;
using System.IO;
using System.Xml;
public class Sample
{
public static void Main()
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" +
"<title>Pride And Prejudice</title>" +
"</book>");
//Create a CData section.
XmlCDataSection CData;
CData = doc.CreateCDataSection("All\r\n Jane\r\n Austen novels 25% off starting 3/23!");
//Add the new node to the document.
XmlElement root = doc.DocumentElement;
root.AppendChild(CData);
Console.WriteLine("Display the modified XML...");
doc.Save(Console.Out);
}
}
Upvotes: 1
Reputation: 4992
You are not in HTML, but in C#. Just use the appropriate string character escape sequence. If you don't know the exact escape sequence letter, just use the corresponding ASCII code or Unicode escape instead, e.g. \x0D
or \x000D
. (13 decimal is 0D hexadecimal)
Upvotes: 0