how to create an XML document like this?
<body> <level1> <level2>text</level2> <level2>other text</level2> </level1> </body>
using XmlDocument
in C#
There are two ways to create an XML document. One way is to create an XmlDocument with no parameters. The other way is to create an XmlDocument and pass it an XmlNameTable as a parameter. The following example shows how to create a new, empty XmlDocument using no parameters.
C# XmlDocument tutorial shows how to work with XML in C# with XmlDocument. Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. XML is often used for application configuration, data storage and exchange.
What about:
#region Using Statements using System; using System.Xml; #endregion class Program { static void Main( string[ ] args ) { XmlDocument doc = new XmlDocument( ); //(1) the xml declaration is recommended, but not mandatory XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration( "1.0", "UTF-8", null ); XmlElement root = doc.DocumentElement; doc.InsertBefore( xmlDeclaration, root ); //(2) string.Empty makes cleaner code XmlElement element1 = doc.CreateElement( string.Empty, "body", string.Empty ); doc.AppendChild( element1 ); XmlElement element2 = doc.CreateElement( string.Empty, "level1", string.Empty ); element1.AppendChild( element2 ); XmlElement element3 = doc.CreateElement( string.Empty, "level2", string.Empty ); XmlText text1 = doc.CreateTextNode( "text" ); element3.AppendChild( text1 ); element2.AppendChild( element3 ); XmlElement element4 = doc.CreateElement( string.Empty, "level2", string.Empty ); XmlText text2 = doc.CreateTextNode( "other text" ); element4.AppendChild( text2 ); element2.AppendChild( element4 ); doc.Save( "D:\\document.xml" ); } }
(1) Does a valid XML file require an xml declaration?
(2) What is the difference between String.Empty and “” (empty string)?
The result is:
<?xml version="1.0" encoding="UTF-8"?> <body> <level1> <level2>text</level2> <level2>other text</level2> </level1> </body>
But I recommend you to use LINQ to XML which is simpler and more readable like here:
#region Using Statements using System; using System.Xml.Linq; #endregion class Program { static void Main( string[ ] args ) { XDocument doc = new XDocument( new XElement( "body", new XElement( "level1", new XElement( "level2", "text" ), new XElement( "level2", "other text" ) ) ) ); doc.Save( "D:\\document.xml" ); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With