It is a very stupid method, but can help beginners understand the process of accessing the XML node. One XML file is known (bookstore.xml) is as follows:
XML Version = "1.0" encoding = "GB2312"?>
1. Insert a
XmlDocument xmlDoc = new XmlDocument (); xmlDoc.Load ( "bookstore.xml"); XmlNode root = xmlDoc.SelectSingleNode ( "bookstore"); // Find
/ / ================ result is:
XML Version = "1.0" encoding = "GB2312"?>
XmlNodelist NodeList = XmLDoc.selectsinglenode ("BookStore"). ChildNodes; // Get all child nodes for the BookStore node Foreach (XMLNode Xn In nodelist) // Traverse all child nodes {xmlelement XE = (xmlelement) xn; // Fander node Type Convert to XMLELEMENT Type IF (Xe.GetaTRibute ("Genre") == "Li Zanhong") // If the GENRE attribute value is "Li Zanhong" {xe.setttribute ("genre", "Update Li Zan Hong"); // Modify This property is "Update Li Zanli" XMLNodeList NLS = Xe.childNodes; / / Continue all child nodes of the XE child node Foreach (XMLNode XN1 IN NLS) // Traversed {XMLELEMENT XE2 = (XMLELEMENT) XN1; // Conversion Type IF ( XE2.NAME == "Author") // If {xe2.innertext = "Assembly"; // modify break; // can be used to find out.}} Break;}} xmldoc.save XML "); // Save.
/ / =================
The last result is:
XML Version = "1.0" encoding = "GB2312"?>
XMLNodeList XNL = XmLDoc.selectsinglenode ("BookStore"). ChildNodes; Foreach (XMLNode XN IN XL) {XMLELEMENT XE = (XMLElement) xn;
IF (Xe.GetaTribute ("genre") == "fantasy")
{
Xe.Removettribute ("genre"); // Delete GENRE attribute
}
Else IF (Xe.GetaTRibute ("genre") == "Update Li Zanli")
{
Xe.removeAll (); // Delete the entire content of the node
}
}
XMLDoc.save ("BookStore.xml");
/ / =====================
The last result is:
XML Version = "1.0" encoding = "GB2312"?>
4, display all data.
XmlNode xn = xmlDoc.SelectSingleNode ( "bookstore"); XmlNodeList xnl = xn.ChildNodes; foreach (XmlNode xnf in xnl) {XmlElement xe = (XmlElement) xnf; Console.WriteLine (xe.GetAttribute ( "genre")); / / Display Attribute Value Console.Writeline ("ISBN")); XMLNodelist XNF1 = Xe.ChildNodes; Foreach (XMLNode XN2 in Xnf1) {Console.WriteLine (xn2.innertext); // Display sub-node text} } Reprinted from: http://blog.9cbs.net/s98/archive/2004/10/17/140307.aspx xmldocument xmldoc = new xmldocument (); xmldoc.load ("c: /aaa.xml"); XMLNode xn = xmlDoc.SelectSingleNode ( "todate"); XmlNodeList xnl = xn.ChildNodes; foreach (XmlNode xnf in xnl) {XmlElement xe = (XmlElement) xnf; XmlNodeList xnf1 = xe.ChildNodes; Response.Write (xnf1 [0]. InnerText); // Display sub-node text}
XmlDocument xmlDoc = new XmlDocument (); xmlDoc.Load ( "c: /aaa.xml"); XmlNode xn = xmlDoc.SelectSingleNode ( "todate"); XmlNodeList xnl = xn.ChildNodes; foreach (XmlNode xnf in xnl) {XmlElement XE = (XMLELEMENT) XNF; XMLNodelist XNF1 = XE.ChildNodes; XNF1 [0] .INNNERTEXT = "10"; XMLDoc.save ("C: /AAA.XML");