ASP.Net/XML/XPath

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

Finding a Particular Node in an XML Document?

   <source lang="csharp">

<%@ Page language="c#" AutoEventWireup="true" %> <%@ Import Namespace="System.Data" %> <script language="C#" runat="server"> protected System.Xml.XmlDocument xmlSource = new System.Xml.XmlDocument(); private void LoadButton_Click(object sender, System.EventArgs e) {

   System.IO.Stream xmlDocStream = GetXmlDoc(XmlSourceTextBox.Text);
   if(xmlDocStream!=null) {
   xmlSource.Load(xmlDocStream);
   ResultText.Text=xmlSource.InnerXml;
   } 
   else 
   {
     ResultText.Text="Could not resolve the XML document.";
   }

}

public static System.IO.Stream GetXmlDoc(string xmlsource) {

   System.IO.Stream stream=null;
   if(xmlsource.StartsWith("<?xml") || xmlsource.StartsWith("<schema") ) 
   {
   stream = new System.IO.MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(xmlsource));
   } 
   else 
   {
   try 
   {
     System.Uri xmluri = new System.Uri(xmlsource);          
     if(xmluri.IsFile) {
         stream = new System.IO.FileStream(xmlsource, System.IO.FileMode.Open);
     } else {
         System.Net.HttpWebRequest request =  (System.Net.HttpWebRequest) System.Net.WebRequest.Create(xmluri);
         System.Net.WebResponse response = request.GetResponse();      
         stream = response.GetResponseStream();
     }
   }
   catch(Exception e) 
   {
   }
   }
   return stream;

} private void QueryButton_Click(object sender, System.EventArgs e) {

   System.Text.StringBuilder s = new System.Text.StringBuilder();
   if(xmlSource==null || xmlSource.InnerText=="") xmlSource.LoadXml(ResultText.Text);
   try 
   {
   System.Xml.XmlNodeList nl = xmlSource.SelectNodes(XPathText.Text);
   int counter=1;
   foreach(System.Xml.XmlNode node in nl) 
   {
     s.Append(counter + "]" + node.InnerText + System.Environment.NewLine);
     counter++;
   }
   QueryResult.Text=s.ToString();
   }
   catch(Exception selectNodesError) 
   {
   QueryResult.Text=selectNodesError.ToString();
   }

} </script> <HTML>

 <HEAD>
   <title>Finding a Particular Node in an XML Document</title>
 </HEAD>
 <body>
   <form id="Form1" method="post" runat="server">
     <asp:textbox id="XmlSourceTextBox" runat="server" Width="379px" Height="162px" TextMode="MultiLine"></asp:textbox>
<asp:button id="LoadButton" runat="server" Text="Load XML Document" OnClick="LoadButton_Click"></asp:button>
<asp:TextBox id="ResultText" runat="server" Width="379px" Height="194px" TextMode="MultiLine"></asp:TextBox>
<asp:Button id="QueryButton" runat="server" Text="Query" OnClick="QueryButton_Click"></asp:Button>
<asp:TextBox id="XPathText" runat="server" Width="379px"></asp:TextBox>
<asp:TextBox id="QueryResult" runat="server" TextMode="MultiLine" Height="229px" Width="379"></asp:TextBox> </form> </body>

</HTML>

</source>
   
  


Finding a Particular Node in an XML Document (VB)

   <source lang="csharp">

<%@ Page language="vb" AutoEventWireup="true" %> <%@ Import Namespace="System.Data" %> <script language="vb" runat="server"> Protected xmlSource As New System.Xml.XmlDocument()

Private Sub LoadButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

   Dim xmlDocStream As System.IO.Stream = GetXmlDoc(XmlSourceTextBox.Text)
   If Not (xmlDocStream Is Nothing) Then
   xmlSource.Load(xmlDocStream)
   ResultText.Text = xmlSource.InnerXml
   Else
   ResultText.Text = "Could not resolve the XML document."
   End If

End Sub Public Shared Function GetXmlDoc(ByVal xmlsource As String) As System.IO.Stream

   Dim stream As System.IO.Stream = Nothing
   If xmlsource.StartsWith("<?xml") Or xmlsource.StartsWith("<schema") Then
   stream = New System.IO.MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(xmlsource))
   Else
   Try
     Dim xmluri As New System.Uri(xmlsource)
     If xmluri.IsFile Then
         stream = New System.IO.FileStream(xmlsource, System.IO.FileMode.Open)
     Else
         Dim request As System.Net.HttpWebRequest = CType(System.Net.WebRequest.Create(xmluri), System.Net.HttpWebRequest)
         Dim response As System.Net.WebResponse = request.GetResponse()
         stream = response.GetResponseStream()
     End If
   Catch e As Exception
   End Try "not a valid uri
   End If
   Return stream

End Function Private Sub QueryButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

   Dim s as new System.Text.StringBuilder()
   
   If xmlSource Is Nothing Or xmlSource.InnerText = "" Then
   xmlSource.LoadXml(ResultText.Text)
   End If
   Try
   Dim nl As System.Xml.XmlNodeList = xmlSource.SelectNodes(XPathText.Text)
   Dim counter As Integer = 1
   Dim node As System.Xml.XmlNode
   For Each node In nl
     s.Append(Convert.ToString(counter) + "]" + node.InnerText + System.Environment.NewLine)
         
     counter += 1
   Next node
   QueryResult.Text=s.ToString()
   Catch selectNodesError As Exception
     QueryResult.Text = selectNodesError.ToString()
   End Try

End Sub </script> <HTML>

 <HEAD>
   <title>Finding a Particular Node in an XML Document</title>
 </HEAD>
 <body>
   <form id="Form1" method="post" runat="server">
     <asp:textbox id="XmlSourceTextBox" runat="server" Width="379px" Height="162px" TextMode="MultiLine"></asp:textbox>
<asp:button id="LoadButton" runat="server" Text="Load XML Document" OnClick="LoadButton_Click"></asp:button>
<asp:TextBox id="ResultText" runat="server" Width="379px" Height="194px" TextMode="MultiLine"></asp:TextBox>
<asp:Button id="QueryButton" runat="server" Text="Query" OnClick="QueryButton_Click"></asp:Button>
<asp:TextBox id="XPathText" runat="server" Width="379px"></asp:TextBox>
<asp:TextBox id="QueryResult" runat="server" TextMode="MultiLine" Height="229px" Width="379"></asp:TextBox> </form> </body>

</HTML>

</source>
   
  


Use XML Path to locate Node and edit its value

   <source lang="csharp">

<%-- Code Revised from

Professional ASP.NET 2.0 XML (Programmer to Programmer) (Paperback) by Thiru Thangarathinam

  1. Publisher: Wrox (January 18, 2006)
  2. Language: English
  3. ISBN: 0764596772

--%>


<%@ Page Language="C#" %> <%@ Import Namespace="System.Xml" %> <%@ Import Namespace="System.Xml.XPath" %> <script runat="server">

   void Page_Load(object sender, EventArgs e)
   {
       //Set the ContentType to XML to write XML values
       Response.ContentType = "text/xml";
       string xmlPath = MapPath("MyBooks.xml");
       XmlDocument document = new XmlDocument();        
       document.Load(xmlPath);
       XPathNavigator navigator = document.CreateNavigator();
       int count = navigator.Select("/bookstore/book").Count;
       //Navigate to the right nodes
       navigator.MoveToChild("bookstore", "");
       navigator.MoveToChild("book", "");
       //Loop through all the book nodes
       for(int i = 0; i < count; i++)
       {                   
           navigator.MoveToChild("price", "");
           double discount = navigator.ValueAsDouble +1;            
           navigator.CreateAttribute("", "discount", "", discount.ToString());
           //Move to the parent book element
           navigator.MoveToParent();
           //Move to the next sibling book element
           navigator.MoveToNext();            
       }
       navigator.MoveToRoot();
       Response.Write (navigator.OuterXml);
   }    

</script>


      </source>
   
  


Use XPathNavigator to create attribute

   <source lang="csharp">

<%-- Code Revised from

Professional ASP.NET 2.0 XML (Programmer to Programmer) (Paperback) by Thiru Thangarathinam

  1. Publisher: Wrox (January 18, 2006)
  2. Language: English
  3. ISBN: 0764596772

--%>

<%@ Page Language="C#" %> <%@ Import Namespace="System.Xml" %> <%@ Import Namespace="System.Xml.XPath" %> <script runat="server">

   void Page_Load(object sender, EventArgs e)
   {
       //Set the ContentType to XML to write XML values
       Response.ContentType = "text/xml";
       string xmlPath = MapPath("MyBooks.xml");
       XmlDocument document = new XmlDocument();        
       document.Load(xmlPath);
       XPathNavigator navigator = document.CreateNavigator();
       int count = navigator.Select("/bookstore/book").Count;
       //Navigate to the right nodes
       navigator.MoveToChild("bookstore", "");
       navigator.MoveToChild("book", "");
       //Loop through all the book nodes
       for(int i = 0; i < count; i++)
       {                   
           navigator.MoveToChild("price", "");
           double discount = navigator.ValueAsDouble +1;            
           navigator.CreateAttribute("", "discount", "", discount.ToString());
           //Move to the parent book element
           navigator.MoveToParent();
           //Move to the next sibling book element
           navigator.MoveToNext();            
       }
       navigator.MoveToRoot();
       Response.Write (navigator.OuterXml);
   }    

</script>

      </source>
   
  


Use XPath to read XML document

   <source lang="csharp">

<%-- Code Revised from

Professional ASP.NET 2.0 XML (Programmer to Programmer) (Paperback) by Thiru Thangarathinam

  1. Publisher: Wrox (January 18, 2006)
  2. Language: English
  3. ISBN: 0764596772

--%>


<%@ Page Language="C#" %> <%@ Import Namespace="System.Xml" %> <script runat="server">

   void Page_Load(object sender, EventArgs e)
   {
       if (!Page.IsPostBack)
       {            
           ddlExpressions.Items.Add("//book/title");
           ddlExpressions.Items.Add("//book[@genre="novel"]/title");
           ddlExpressions.Items.Add("//book/author/first-name");
           ddlExpressions.Items.Add("//book[@genre="philosophy"]/title");
           ddlExpressions.Items.Add("//book/price");
           ddlExpressions.Items.Add("//book[3]/title");
           ddlExpressions.SelectedIndex = 0;
           UpdateDisplay();
       }
   }
   void ddlExpressions_SelectedIndexChanged(object sender, EventArgs e)
   {
       UpdateDisplay();
   }
   void UpdateDisplay()
   {
       lstOutput.Items.Clear();
       string xmlPath = MapPath("MyBooks.xml");
       XmlDocument doc = new XmlDocument();
       doc.Load(xmlPath);
       XmlNodeList nodeList = doc.DocumentElement.SelectNodes(ddlExpressions.SelectedItem.Text);
       foreach (XmlNode child in nodeList)
       {
           lstOutput.Items.Add("Node Name:" + child.Name);
           lstOutput.Items.Add("Node Value:" + child.FirstChild.Value);
       }
   }

</script> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

   <title>XPath Example</title>

</head> <body>

   <form id="form1" runat="server">
       Select the XPath Expression:
       <asp:DropDownList ID="ddlExpressions" AutoPostBack="true" runat="server" Width="410px" OnSelectedIndexChanged="ddlExpressions_SelectedIndexChanged">
       </asp:DropDownList>    
       

<asp:ListBox ID="lstOutput" runat="server" Width="587px" Height="168px"></asp:ListBox>
   </form>

</body> </html>

<%-- <?xml version="1.0"?> <bookstore>

 <book genre="autobiography">
   <title>The Autobiography</title>
   <author>
     <first-name>A</first-name>
     <last-name>B</last-name>
   </author>
   <price>999</price>
 </book>
 <book genre="novel">
   <title>The Man</title>
   <author>
     <first-name>C</first-name>
     <last-name>D</last-name>
   </author>
   <price>8888</price>
 </book>

</bookstore>

--%>

      </source>
   
  


Using the XPathNavigator for Navigating Xml Documents

   <source lang="csharp">

<%@ Import Namespace="System" %> <%@ Import Namespace="System.Xml" %> <%@ Import Namespace="System.Xml.XPath" %> <%@ Page Language="C#" %> <script runat="server">

   private void Page_Load(Object Source, EventArgs E)
   {
       StringBuilder sb = new StringBuilder();
       String space2 = "  ";
       String space3 = "   ";
   
       XmlDocument _XmlDoc = new XmlDocument();
       _XmlDoc.Load(Server.MapPath("Data.xml"));
   
       XPathNavigator _Nav;
       _Nav = _XmlDoc.CreateNavigator();
   
       _Nav.MoveToRoot();
       sb.Append("Root: ");
       sb.Append("name=" + _Nav.Name + ", type=" + _Nav.NodeType.ToString());
       sb.Append("

"); _Nav.MoveToFirstChild(); sb.Append("name=" + _Nav.Name + ", type=" + _Nav.NodeType.ToString()); sb.Append("
"); _Nav.MoveToFirstChild(); do { sb.Append(space2); sb.Append("name=" + _Nav.Name + ", type=" + _Nav.NodeType.ToString()); sb.Append("
"); _Nav.MoveToFirstAttribute(); sb.Append(space2); sb.Append("Attribute: " + _Nav.Name + "=" + _Nav.Value); sb.Append("
"); _Nav.MoveToParent(); _Nav.MoveToFirstChild(); do { sb.Append(space3); sb.Append("name=" + _Nav.Name + ", type=" + _Nav.NodeType.ToString() + ", value=" + _Nav.Value); sb.Append("
"); }while(_Nav.MoveToNext()); _Nav.MoveToParent(); }while(_Nav.MoveToNext()); OutputLiteral.Text = sb.ToString(); }

</script> <html> <head> <title>Using the XPathNavigator for Navigating Xml Documents</title> </head> <body>

   <form runat="server">
       
       <asp:Literal id="OutputLiteral" runat="server"></asp:Literal>
   </form>

</body> </html> File: Data.xml <?xml version="1.0" encoding="utf-8" ?> <users>

 <user role="admin">
   <username>jsmith</username>
   <password>john</password>
 </user>
 <user role="operator">
   <username>tcruise</username>
   <password>tom</password>
 </user>

</users>

</source>
   
  


XPathNavigator Selection Example

   <source lang="csharp">

<%-- Code Revised from

Professional ASP.NET 2.0 XML (Programmer to Programmer) (Paperback) by Thiru Thangarathinam

  1. Publisher: Wrox (January 18, 2006)
  2. Language: English
  3. ISBN: 0764596772

--%>


<%@ Page Language="C#" %> <%@ Import Namespace="System.Xml" %> <script runat="server">

   void Page_Load(object sender, EventArgs e)
   {
       if (!Page.IsPostBack)
       {            
           ddlExpressions.Items.Add("//book/title");
           ddlExpressions.Items.Add("//book[@genre="novel"]/title");
           ddlExpressions.Items.Add("//book/author/first-name");
           ddlExpressions.Items.Add("//book[@genre="philosophy"]/title");
           ddlExpressions.Items.Add("//book/price");
           ddlExpressions.Items.Add("//book[3]/title");
           ddlExpressions.SelectedIndex = 0;
           UpdateDisplay();
       }
   }
   void ddlExpressions_SelectedIndexChanged(object sender, EventArgs e)
   {
       UpdateDisplay();
   }
   void UpdateDisplay()
   {
       lstOutput.Items.Clear();
       string xmlPath = MapPath("MyBooks.xml");
       XmlDocument doc = new XmlDocument();
       doc.Load(xmlPath);
       XmlNodeList nodeList = doc.DocumentElement.SelectNodes(ddlExpressions.SelectedItem.Text);
       foreach (XmlNode child in nodeList)
       {
           lstOutput.Items.Add("Node Name:" + child.Name);
           lstOutput.Items.Add("Node Value:" + child.FirstChild.Value);
       }
   }

</script> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

   <title>XPath Example</title>

</head> <body>

   <form id="form1" runat="server">
       Select the XPath Expression:
       <asp:DropDownList ID="ddlExpressions" AutoPostBack="true" runat="server" Width="410px" OnSelectedIndexChanged="ddlExpressions_SelectedIndexChanged">
       </asp:DropDownList>    
       

<asp:ListBox ID="lstOutput" runat="server" Width="587px" Height="168px"></asp:ListBox>
   </form>

</body> </html>

<%-- <?xml version="1.0"?> <bookstore>

 <book genre="autobiography">
   <title>The Autobiography</title>
   <author>
     <first-name>A</first-name>
     <last-name>B</last-name>
   </author>
   <price>999</price>
 </book>
 <book genre="novel">
   <title>The Man</title>
   <author>
     <first-name>C</first-name>
     <last-name>D</last-name>
   </author>
   <price>8888</price>
 </book>

</bookstore>

--%>

      </source>