Saturday, July 10, 2010

How To Create XML Object in C#




XmlDocument xDoc = new XmlDocument();
XmlElement root = null;
XmlElement node = null;
XmlAttribute att = null;

// Create XML declaration
XmlNode declaration = xDoc.CreateNode(XmlNodeType.XmlDeclaration, null, null);
declaration.Value = "version=\"1.0\" encoding=\"utf-8\"";
xDoc.AppendChild(declaration);


// Create Child Element with two attributes id and name
node = xDoc.CreateElement("node");

att = xDoc.CreateAttribute("id");
att.Value = "100";
node.Attributes.Append(att);

att = xDoc.CreateAttribute("name");
att.Value = "data_100";
node.Attributes.Append(att);

// Create data content which encapesole in <![CDATA[[ ]]> section.
XmlCDataSection CData = xDoc.CreateCDataSection("This text contains some xml escape characters & < > ' \" which encapsolete in CDATA.");

node.AppendChild(CData);

// Create root Element
root = xDoc.CreateElement("root");


root.AppendChild(node);

xDoc.AppendChild(root);



// Get XML string from XmlDocument
string xmlStr = xDoc.outerXml;

the result of xmlStr will be like this:
<?xml version="1.0" encoding="utf-8"?>
<root>
    <node id="100" name="data_100" >
        <![CDATA [This text contains some xml escape characters & < > ' " which encapsolete in CDATA.]]>
    </node>
</root>

No comments: