public void TestXML() { XmlDocument doc = new XmlDocument(); string path = "http://www.cnblogs.com/MyDocument/Person.xml" ; try { //doc.Load(Server.MapPath() doc.Load(path); //1、读取单个节点的数据 XmlNode node = doc.SelectSingleNode( "PersonF" ); //2、读取多个节点的数据 XmlNodeList nodeList1 = doc.SelectNodes( "PersonF/person" ); //3.1 读取具体节点的具体值 如:属性为Person2的第二个节点Name的InnerText XmlNodeList nodeList = doc.DocumentElement.GetElementsByTagName( "person" ); foreach (XmlNode node2 in nodeList1) //当然也能用nodeList的值 { if (node2.Attributes[ "Name" ].InnerText == "Person2" ) { Console.WriteLine(node2.ChildNodes[1].InnerText); } } //3.2 读取ID为2所在的节点第二个子节点Name的InnerText XmlNode node3 = doc.SelectSingleNode( "PersonF/person[ID=2]" ); string strNode3 = node3.ChildNodes[1].InnerText; //3.3利用下面的方法可以找到ID为2的节点 XmlNodeList nodeList2 = doc.SelectNodes( "//person//ID" ); XmlNode node4 = null ; foreach (XmlNode node5 in nodeList2) { if (node5.InnerText == "2" ) { node4 = node5; break ; } } Console.WriteLine(node4.InnerText); //4、读取节点的属性 string Name = node.Attributes[ "Name" ].InnerText; //5 修改节点的属性 node.Attributes[ "Name" ].InnerText = "work hard work smart!" ; doc.Save(path); //6 添加自定义的节点 XmlTextReader reader = new XmlTextReader(path); XmlElement root = doc.DocumentElement; //获取根节点 XmlElement tagOuter = doc.CreateElement( "person" ); //设置节点属性 tagOuter.SetAttribute( "Name" , "Person5" ); XmlElement tagIN_Name = doc.CreateElement( "Name" ); XmlElement tagIN_ID = doc.CreateElement( "ID" ); tagIN_Name.InnerText = "work hard work smart!" ; tagIN_ID.InnerText = "32" ; tagOuter.AppendChild(tagIN_Name); tagOuter.AppendChild(tagIN_ID); root.AppendChild(tagOuter); //添加tagOuter到XML文件的最后 reader.Close(); doc.Save(path); } catch (System.Exception e) { throw new Exception(e.Message); } } |