C#使用XmlDocument或XDocument創(chuàng)建xml文件
使用XmlDocument或XDocument創(chuàng)建xml文件,具體內(nèi)容如下
需引用:System.Xml; System.Xml.Linq;
1.使用XmlDocument創(chuàng)建xml(入門案例)
static void Main(string[] args)
{
//使用XmlDocument創(chuàng)建xml
XmlDocument xmldoc = new XmlDocument();
XmlDeclaration xmldec = xmldoc.CreateXmlDeclaration("1.0", "utf-8", "yes");
xmldoc.AppendChild(xmldec);
//添加根節(jié)點(diǎn)
XmlElement rootElement = xmldoc.CreateElement("school");
xmldoc.AppendChild(rootElement);
//添加根節(jié)點(diǎn)下的子節(jié)點(diǎn)元素
XmlElement classElement = xmldoc.CreateElement("class");
rootElement.AppendChild(classElement);
XmlAttribute atrrClass = xmldoc.CreateAttribute("No");
atrrClass.Value = "1";
classElement.Attributes.Append(atrrClass);
//添加子節(jié)點(diǎn)下的元素
XmlElement stuElement = xmldoc.CreateElement("student");
classElement.AppendChild(stuElement);
XmlAttribute attrStu = xmldoc.CreateAttribute("sid");
attrStu.Value = "20180101";
stuElement.Attributes.Append(attrStu);
//保存文件
xmldoc.Save(@"d:\zzz\TestA.xml");
Console.WriteLine("創(chuàng)建xml文件ok!");
Console.ReadKey();
}
使用XmlDocument創(chuàng)建的xml文件:

2. 使用XDocument創(chuàng)建xml(入門案例)
static void Main(string[] args)
{
//使用XDocument創(chuàng)建xml
System.Xml.Linq.XDocument xdoc = new XDocument();
XDeclaration xdec = new XDeclaration("1.0", "utf-8", "yes");
xdoc.Declaration = xdec;
//添加根節(jié)點(diǎn)
XElement rootEle = new XElement("school");
xdoc.Add(rootEle);
//給根節(jié)點(diǎn)添加子節(jié)點(diǎn)
XElement classEle = new XElement("class");
XAttribute attrClass = new XAttribute("No", 1);
classEle.Add(attrClass);
rootEle.Add(classEle);
//添加子節(jié)點(diǎn)下的元素
XElement stuEle = new XElement("student");
XAttribute atrStu = new XAttribute("sid", "20180101");
stuEle.Add(atrStu);
classEle.Add(stuEle);
//保存文件
xdoc.Save("d:\\zzz\\TestB.xml");
Console.WriteLine("創(chuàng)建xml文件ok");
Console.ReadKey();
}
使用XDocument創(chuàng)建的Xml文件:

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
c# socket心跳超時(shí)檢測(cè)的思路(適用于超大量TCP連接情況下)
這篇文章主要介紹了c# socket心跳超時(shí)檢測(cè)的思路(適用于超大量TCP連接情況下),幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03
C#中隱藏TabControl選項(xiàng)卡標(biāo)簽的解決方案
這篇文章主要介紹了C#中隱藏TabControl選項(xiàng)卡標(biāo)簽的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04
unity 如何使用文件流讀取streamingassets下的資源
這篇文章主要介紹了unity 使用文件流讀取streamingassets下的資源操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-04-04
C#結(jié)合JavaScript實(shí)現(xiàn)秒殺倒計(jì)時(shí)的方法
這篇文章主要介紹了C#結(jié)合JavaScript實(shí)現(xiàn)秒殺倒計(jì)時(shí)的方法,涉及C#結(jié)合javascript操作時(shí)間的技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04

