<body> <level1> <level2>text</level2> <level2>other text</level2> </level1></body>
在C#中使用Xmldocument
解决方法 关于什么:#region Using Statementsusing 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,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)?
结果是:
<?xml version="1.0" enCoding="UTF-8"?><body> <level1> <level2>text</level2> <level2>other text</level2> </level1></body>
但我建议你使用更简单,更易读的LINQ to XML,如下所示:
#region Using Statementsusing 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" ),"other text" ) ) ) ); doc.Save( "D:\document.xml" ); }}总结
以上是内存溢出为你收集整理的c# – 如何使用XmlDocument创建XML文档?全部内容,希望文章能够帮你解决c# – 如何使用XmlDocument创建XML文档?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)