0

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?

1
  • Linq2Xml Commented Sep 11, 2012 at 20:26

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You can try using WriteCData

Pseudo:

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.