添加引用node
using System.Xml;
建立XML文件spa
XmlDocument xmldoc=new XmlDocument(); //加入XML的聲明段落:<?xmlversion="1.0" encoding="utf-8"?> XmlDeclaration xmldecl=xmldoc.CreateXmlDeclaration("1.0", "utf-8", null); xmldoc.AppendChild(xmldecl); //保存建立好的XML文檔 xmldoc.Save(@"D:\user.xml");
加載XML文件code
//方法一:Lode方法加載的是XML文件所在的路徑 xmldoc.Load(@"D:\user.xml"); //方法二:LoadXml方法加載的是XML字符串 xmldoc.LoadXml("<user></user>");
建立節點xml
//建立根節點 XmlElement xmlroot = xmldoc.CreateElement("user"); xmldoc.AppendChild(xmlroot); //建立根節點的子節點
XmlElement ePerson=xmldoc.CreateElement("person");
xmlroot.AppendChild(ePerson);
獲取節點blog
//獲取根節點 XmlElement root = xmldoc.DocumentElement; //獲取單個節點:若是有篩選到多個符合條件的,默認選第一個 XmlNode node=xmldoc.SelectSingleNode("user");//方法一:獲取標籤名爲:user的節點 XmlNode node=xmldoc.SelectNodes("user").Item(0);//方法二:這種方法須要瞭解節點排列順序才能夠準確的獲取想要的節點 XmlNode node=xmldoc.SelectSingleNode("user/person[@name='王五']")//方法三:指定了屬性,進一步篩選 //獲取該路徑下全部節點的集合 XmlNodeList nodelist=xmldoc.SelectNodes("user/person");//方法一:獲取user節點下的person節點集合 XmlNodeList nodelist=xmldoc.SelectSingleNode("user").ChildNodes;//方法二:獲取user節點下的全部子節點 XmlNodeList nodelist=xmlroot.GetElementsByTagName("person")//方法三:獲取根節點下的標籤名爲person的節點集合 //遍歷節點 foreach(XmlNode childNode in nodelist) { Response.Write(childNode .Name); }
刪除節點utf-8
//刪除其下全部節點和其自己的屬性以(只剩下標籤) 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(); //方法三:XmlNode.SelectSingleNode()方法中,節點名加@表示查找屬性,但最後要轉成(XmlAttribute) XmlAttribute xa = (XmlAttribute)person.SelectSingleNode("@" + name); string name=xa.Value.ToString();
刪除屬性string
//方法一:刪除指定屬性 person.RemoveAttribute("age"); //方法二:刪除某個位置的屬性(須要瞭解屬性的順序) person.RemoveAttributeAt(0); //方法三:刪除全部屬性 person.RemoveAllAttributes();
XmlNode和XmlElement比較it
XmlElement是XmlNode的子類。
Xml節點有多種類型:屬性節點、註釋節點、文本節點、元素節點等。XmlNode是這多種節點的統稱,可是XmlElement專門指的就是元素節點。
XmlElement是具現類,能夠直接實例化,而XmlNode是抽象類。