ASP.Net/XML/Query

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Use XML Document to Query for specific nodes

<%@ 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">" +    
                    "<firstName>First Name</firstName>" + 
                    "<lastName>Last Name</lastName>" +                       
                    "<city>City</city>" +
                    "<state>WA</state><zipCode>99999</zipCode>" +
            "</employee></employees>");         
        
        //Get all job titles in the XML file
        XmlNodeList titleList = doc.GetElementsByTagName("employee");
        Response.Write("Employee: " + "<br>");
        foreach (XmlNode node in titleList)
        {
            Response.Write("Title : " + node.FirstChild.Value + "<br>");
        }
        //Get reference to the first author node in the XML file
        XmlNode authorNode = doc.GetElementsByTagName("employee")[0];
        foreach (XmlNode child in authorNode.ChildNodes)
        {
            if ((child.Name == "firstName") && (child.NodeType == XmlNodeType.Element))
            {
                Response.Write("First Name : " + child.FirstChild.Value + "<br>");
            }
            if ((child.Name == "lastName") && (child.NodeType == XmlNodeType.Element))
            {
                Response.Write("Last Name : " + child.FirstChild.Value + "<br>");
            }
        }
    }    
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Querying for specific nodes</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>