您可以使用此代碼 - 基於XmlTextWriter class
XmlTextWriter textWriter = new XmlTextWriter("yourpath", null);
// Opens the document
textWriter.WriteStartDocument();
textWriter.WriteStartElement("root");
textWriter.WriteAttributeString("xmlns", "x", null, "urn:1");
// Write comments
textWriter.WriteComment("First Comment XmlTextWriter Sample Example");
textWriter.WriteEndElement();
// Ends the document.
textWriter.WriteEndDocument();
// close writer
textWriter.Close();
鏈接:http://msdn.microsoft.com/fr-fr/library/system.xml.xmltextwriter.aspx
您還可以使用LINQ到XML
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XComment("This is a test"),
new XElement("root")
);
var root = doc.CreateElement("Test");
....
鏈接:http://msdn.microsoft.com/en-us/library/bb387098.aspx
我試圖使相同但它給了我這個錯誤:XML文檔必須h成爲頂級元素。處理資源'file:/// D:/DEV/Gen_Lic.xml'時出錯。 – Esha
您使用XDocument doc = new XDocument創建了根Xelement(「root」)新的XComment(「This is a test」), 新的XDeleration(「1.0」,「utf-8」,「yes」 ); –
我用這個創建了我的xml文件:'XmlWriter writer = XmlWriter.Create(「D:\\ DEV \\ Gen_Lic.xml」);' – Esha