Table of Contents

IT:AD:NET:HowTo:Serialization:XML

XElement

Loading

XElement doc = XElement.Load(fileName);

Creating

XElement root = new XElement("client",
  new XElement("ID", "1")
  new XElement("First", "John")
  new XElement("Last", "Smith")
);

Pretty Printing

Regarding Xml/Xslt: How do I use Xslt to transform Xml and keep it indented / pretty printed? The basics are:

//load the Xml doc
XPathDocument myXPathDoc = new XPathDocument(inputXmlFilePath);

//load the Xsl 
XslCompiledTransform xslCompiledTransform = 
  new XslCompiledTransform();
xslCompiledTransform.Load(inputXslFilePath);

//create the output stream
using (XmlTextWriter xmlTextWriter = 
  new XmlTextWriter(outputXmlFilePath, null)) 
{
  //This is the stuff to add to get pretty formatting:
  xmlTextWriter.Formatting = Formatting.Indented;
  xmlTextWriter.IndentChar = ' ';
  xmlTextWriter.Indentation = 2;

   //do the actual transform of Xml
  xslCompiledTransform.Transform(  
    myXPathDoc, null, xmlTextWriter);
    xmlTextWriter.Close();
}