XmlDocument doc = new XmlDocument(); // Load the XML to be read doc.Load(@"F:\Books.xml"); // Get the root node XmlElement books = doc.DocumentElement; // Get the set of nodes returned by the child node XmlNodeList xnl = books.ChildNodes; foreach (XmlNode item in xnl) { XmlElement xe = (XmlElement)item; Console.WriteLine(xe.GetAttribute("id")); XmlNodeList nodeList = xe.ChildNodes; foreach (XmlNode item2 in nodeList) { Console.WriteLine(item2.InnerText); } } Console.ReadKey();
Edit content
XmlDocument doc = new XmlDocument(); doc.Load(@"F:\Books.xml"); XmlNodeList nodeList = doc.SelectSingleNode ( " / Books / Book [@ id = '3d310e87-6c46-4874-859e-c09f3acce589'] " ) .ChildNodes; foreach (XmlNode xn in nodeList) // Traverse all child nodes { XmlElement xe = (XmlElement) xn; // Convert the child node type to XmlElement type // Console.WriteLine (xe.GetAttribute ("id")); if (xe.Name == " Price " ) { Console.WriteLine(xe.InnerText); xe.InnerText = "oooooooo"; } } doc.Save(@"F:\Books.xml");
Modify attributes
// Change the value of the attribute XmlDocument doc = new XmlDocument (); doc.Load("Order.xml"); XmlNode xn = doc.SelectSingleNode("/Order/Items/OrderItem[@Name='190']"); xn.Attributes["Count"].Value = "200"; xn.Attributes["Name"].Value = "颜世伟"; doc.Save("Order.xml"); Console.WriteLine ( " Save successfully " );