Summary

Demonstrates how to create and output a simple XML document.

Code (C#)

// Clear the output editor
Output.Clear();

// Create XML document
XmlDocument xmlDoc = new XmlDocument();

// Add XML declaration tag: <?xml>
XmlDeclaration xmlNode = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
xmlDoc.AppendChild(xmlNode);

// Add root node: <XmlDemo timeStamp="2010-10-08">...</XmlDemo>
XmlElement rootNode = xmlDoc.CreateElement("XmlDemo");
XmlAttribute timeStampAttribute = xmlDoc.CreateAttribute("timeStamp");
timeStampAttribute.Value = DateTime.Now.ToString("yyyy-MM-dd");
rootNode.Attributes.Append(timeStampAttribute);
xmlDoc.AppendChild(rootNode);

// Add sub node: <InputText>...</InputText>
XmlElement inputTextNode = xmlDoc.CreateElement("InputText");
inputTextNode.AppendChild(xmlDoc.CreateTextNode(Input.Text));
rootNode.AppendChild(inputTextNode);

// Write XML content to StringWriter
using (StringWriter stringWriter = new StringWriter())
using (XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter))
{
    xmlTextWriter.Formatting = Formatting.Indented;  // Output formatted XML code
    xmlDoc.WriteTo(xmlTextWriter);
    
    // Output XML code
    Output.Text = stringWriter.ToString();
} 
Input Type: Plain Text, Output Type: Plain Text

Download Project File

File: Introduction_create_XML_document.dvp (2.37 KB)

To open this file, DataVoila must be installed on your computer. If this is not yet the case, please click here to download the free demo version.