Tuesday, January 24, 2012

Adding CDATA - (Unparsed) Character Data to XElement

When working with the System.Linq.Xml namespace, and creating an XDocument you may need to create create document data that  that should not be parsed by the XML parser. For example: data with XML reserved characters, xml content, html content (or really anything you do not want to be parsed).

Creating data within a CDATA tag is simple, simply wrap the content within the XElement in an additional object called XCData.
XDocument contactsDoc =
   new XDocument(
      new XDeclaration("1.0", "utf-8", "yes"),
      new XComment("LINQ to XML Contacts XML Example"),
      new XProcessingInstruction("MyApp", "123-44-4444"),
      new XElement("contacts",
         new XElement("contact",
            new XElement("name", "Patrick Hines"), 
            new XElement("comment", new XCData("ALERT! Do not call!")),
            new XElement("address",
               new XElement("street1", "123 Main St"),
               new XElement("city", "Mercer Island"),
               new XElement("state", "WA"),
               new XElement("postal", "68042")
            )
         )
      )
   );
Sample adapted from .NET Language-Integrated Query for XML Data 
References:
CDATA
.NET Language-Integrated Query for XML Data
XCData Class

No comments: