生活随笔
收集整理的這篇文章主要介紹了
C# XML操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
-
添加引用
using System.Xml;
-
創建XML文件
XmlDocument xmldoc
=new XmlDocument();
XmlDeclaration xmldecl
=xmldoc
.CreateXmlDeclaration("1.0", "utf-8", null
);
xmldoc
.AppendChild(xmldecl
);
xmldoc
.Save(@
"D:\user.xml");
xmldoc
.Load(@
"D:\user.xml");
xmldoc
.LoadXml("<user></user>");
XmlElement xmlroot
= xmldoc
.CreateElement("user");
xmldoc
.AppendChild(xmlroot
);
XmlElement ePerson
=xmldoc
.CreateElement("person");
xmlroot
.AppendChild(ePerson
);
XmlElement root
= xmldoc
.DocumentElement
;
XmlNode node
=xmldoc
.SelectSingleNode("user");
XmlNode node
=xmldoc
.SelectNodes("user").Item(0);
XmlNode node
=xmldoc
.SelectSingleNode("user/person[@name='王五']")
XmlNodeList nodelist
=xmldoc
.SelectNodes("user/person");
XmlNodeList nodelist
=xmldoc
.SelectSingleNode("user").ChildNodes
;
XmlNodeList nodelist
=xmlroot
.GetElementsByTagName("person")
foreach(XmlNode childNode in nodelist
)
{Response
.Write(childNode
.Name
);
}
xmlroot
.RemoveAll();
xmlroot
.RemoveChild(person
);
person
.SetAttribute("name","張三");
person
.Attributes
["name"].Value
= "張三三";
XmlAttribute age
= xmldoc
.CreateAttribute("age");
age
.Value
= "23";
person
.Attributes
.Append(age
);
person
.InnerText
= "123";
string name
=person
.Attributes
["name"].Value
.ToString();
string name
=person
.GetAttribute("name").ToString();
XmlAttribute xa
= (XmlAttribute
)person
.SelectSingleNode("@" + name
);
string name
=xa
.Value
.ToString();
person
.RemoveAttribute("age");
person
.RemoveAttributeAt(0);
person
.RemoveAllAttributes();
XmlElement是XmlNode的子類。
Xml節點有多種類型:屬性節點、注釋節點、文本節點、元素節點等。XmlNode是這多種節點的統稱,但是XmlElement專門指的就是元素節點。
XmlElement是具現類,可以直接實例化,而XmlNode是抽象類。
總結
以上是生活随笔為你收集整理的C# XML操作的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。