进行操作的xml文件:
products.xml
<? xml version="1.0" encoding="utf-8" ?> < products > < product name ="apple" price ="3.50" /> < product name ="banana" price ="2.00" /> </ products >
增加节点:
XmlDocument doc = new XmlDocument(); doc.Load( " products.xml "); XmlNode xn = doc.SelectSingleNode( " products "); XmlElement xe = doc.CreateElement( " product "); xe.SetAttribute( " name ", " haha "); xe.SetAttribute( " price ", " 13.20 "); xn.AppendChild(xe); doc.Save( " products.xml ")
修改节点属性值:
XmlDocument doc = new XmlDocument(); doc.Load( " products.xml "); XmlNode xn = doc.SelectSingleNode( " products "); XmlNodeList xnList = xn.ChildNodes; if(xnList.Count > 0) { for( int i = xnList.Count - 1; i >= 0;i--) { XmlElement xe = (XmlElement)xnList.Item(i); if(xe.Attributes[ " name "].Value == " banana ") { xe.SetAttribute( " price ", " 1111 "); break; } } doc.Save( " products.xml ") }
删除节点:
XmlDocument doc = new XmlDocument(); doc.Load( " products.xml "); XmlNode xn = doc.SelectSingleNode( " products "); XmlNodeList xnList = xn.ChildNodes; if(xnList.Count > 0) { for( int i = xnList.Count - 1; i >= 0;i--) { XmlElement xe = (XmlElement)xnList.Item(i); if(xe.Attributes[ " name "].Value == " banana ") { xn.RemoveChild(xe); } } doc.Save( " products.xml ") }