Mega Code Archive

 
Categories / ASP.Net / XML
 

Traversing the DOM Tree

<%@ Page Language="C#" %> <%@ Import Namespace="System.Xml" %> <script runat="server">     void Page_Load(object sender, EventArgs e)     {         string xmlPath = MapPath("Books.xml");         XmlDocument doc = new XmlDocument();         //doc.Load(xmlPath);         doc.LoadXml("<employees>" +                     "<employee id='1'>" +                         "<name><firstName>First Name</firstName>" +                      "<lastName>Last Name</lastName>" +                                            "</name><city>City</city>" +                     "<state>WA</state><zipCode>99999</zipCode>" +             "</employee></employees>");                  XmlNode rootNode = doc.DocumentElement;                 DisplayNodes(rootNode);             }     void DisplayNodes(XmlNode node)     {         //Print the node type, node name and node value of the node         if (node.NodeType == XmlNodeType.Text) {             Response.Write("Type= [" + node.NodeType+ "] Value=" + node.Value + "<br>");         } else {             Response.Write("Type= [" + node.NodeType+"] Name=" + node.Name + "<br>");         }         //Print attributes of the node         if (node.Attributes != null) {             XmlAttributeCollection attrs = node.Attributes;             foreach (XmlAttribute attr in attrs) {                 Response.Write("Attribute Name =" + attr.Name+ "Attribute Value =" + attr.Value);             }             }         //Print individual children of the node         XmlNodeList children = node.ChildNodes;         foreach (XmlNode child in children)          {             DisplayNodes(child);         }     } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">     <title>Traversing the DOM Tree</title> </head> <body>     <form id="form1" runat="server">     <div>          </div>     </form> </body> </html>