如何使用XmlDocument创buildXML文档?

如何创build这样的XML文件?

<body> <level1> <level2>text</level2> <level2>other text</level2> </level1> </body> 

在C#中使用XmlDocument

关于什么:

 #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) 有效的XML文件是否需要xml声明?
(2) String.Empty和“”(空string)有什么区别?


结果是:

 <?xml version="1.0" encoding="UTF-8"?> <body> <level1> <level2>text</level2> <level2>other text</level2> </level1> </body> 

但是我build议你使用LINQ to XML ,这样更简单,更具可读性。

 #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" ); } }