Tony Trozzo
Tony Trozzo

Reputation: 1231

C# XmlWriter to StringBuilder HTML Entites

I'm currently adding a new node to an XML file. Since the node has to be slightly dynamic, I created a StringBuilder and am using an XmlWriter to create the node:

StringBuilder newDateXML = new StringBuilder();
XmlWriter newDateXMLWriter = XmlWriter.Create(newDateXML, xmlWriterSettings);
newDateXMLWriter.WriteStartElement("Dates");
newDateXMLWriter.WriteElementString("type", "UNDEFINED");
newDateXMLWriter.WriteElementString("value", "YYYYMMDD");
newDateXMLWriter.WriteStartElement("additionalDateFields");
newDateXMLWriter.WriteStartElement("AdditionalDateFields");
newDateXMLWriter.WriteAttributeString("order", "1");
newDateXMLWriter.WriteElementString("type", "Original Type");
newDateXMLWriter.WriteElementString("value", "Date Added");
newDateXMLWriter.WriteEndElement();
newDateXMLWriter.WriteEndElement();
newDateXMLWriter.WriteEndElement();
newDateXMLWriter.Flush();

Whenever I want to add the node, I use these to replace the value I want and add it to the file:

x4.Add(newDateXML.ToString().Replace("YYYYMMDD", dictionary[x3.Element("value").Value]));

where x4 is an XElement and x3 is an XElement containing my lookup value.

The problem is I believe that adding these as a string is turning my '>' into &lt ; and '>' into &gt ;

In order to fix this, I tried replacing them out like this:

foreach (XElement x in currentXML.Descendants("NameAddressRecord"))
{
    newXML.WriteRaw(x.ToString().Replace("&lt;", "<").Replace("&gt;", ">"));
}

But I ran into an issue where some other data is actually using those symbols and converting them is breaking the XML integrity. Is there any way to easily replace out this value without losing the XML formatting and without having to recreate this node each time I want to use it?

Upvotes: 0

Views: 1861

Answers (3)

zykorex
zykorex

Reputation: 46

You can use XElement.Parse() to get the right formatting:

x4.Add(XElement.Parse(newDateXML.ToString().Replace("YYYYMMDD", "20120908")));

I tried this in LinqPad and it seems to be doing the right thing.

Upvotes: 2

Praveen
Praveen

Reputation: 100

Yes you need to write that as Cdatastring. Any thing included with in CDATA, the parser ignores that. so any javascript code or values like the one you mentioned should be in the CDATA section

Upvotes: 0

Roland
Roland

Reputation: 1010

You can try using WriteCData

Pseudo:

newXml.WriteStartElement(x)
newXml.WriteCData(mySTringToStore)
newXml.WriteEndElement

Upvotes: 0

Related Questions