ASP.NET Tutorial/XML/XPath

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

Querying XML with XPathDocument and XPathNodeIterator (C#)

   <source lang="csharp">

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

   <title>Untitled Page</title>

</head> <body>

   <form id="form1" runat="server">
   </form>

</body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.IO; using System.Xml; using System.Xml.XPath; public partial class _Default : System.Web.UI.Page {

   protected void Page_Load(object sender, EventArgs e)
   {
       string booksFile = Path.rubine(Request.PhysicalApplicationPath, "Data.xml");
       XPathDocument document = new XPathDocument(booksFile);
       XPathNavigator nav = document.CreateNavigator();
       XmlNamespaceManager namespaceMgr = new XmlNamespaceManager(nav.NameTable);
       namespaceMgr.AddNamespace("b", "http://example.books.ru");
       foreach (XPathNavigator node in nav.Select("//b:book[not(b:price[. > 10.00])]/b:price",namespaceMgr))
       {
           Decimal price = (decimal)node.ValueAs(typeof(decimal));
           Response.Write(String.Format("Price is {0}
", price)); } }

} File: Data.xml <?xml version="1.0"?> <bookstore xmlns="http://example.books.ru"

          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <book genre="A" 
         publicationdate="1981" 
         ISBN="1-11111-11-0">
       <title>title 1</title>
       <author>
           <first-name>A</first-name>
           <last-name>B</last-name>
       </author>
       <price>8</price>
   </book>
   <book genre="B" 
         publicationdate="1999" 
         ISBN="0-222-22222-2">
       <title>title 2</title>
       <author>
           <first-name>C</first-name>
           <last-name>D</last-name>
       </author>
       <price>11.99</price>
   </book>

</bookstore></source>


Querying XML with XPathDocument and XPathNodeIterator (VB)

   <source lang="csharp">

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

   <title>Untitled Page</title>

</head> <body>

   <form id="form1" runat="server">
   </form>

</body> </html> File: Default.aspx.vb Imports System.IO Imports System.Xml Imports System.Xml.XPath Partial Class _Default

   Inherits System.Web.UI.Page
   Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
          Handles Me.Load
       Dim booksFile As String = Path.rubine(Request.PhysicalApplicationPath, _
           "Data.xml")
       Dim document As New XPathDocument(booksFile)
       Dim nav As XPathNavigator = document.CreateNavigator()
       Dim namespaceMgr As New XmlNamespaceManager(nav.NameTable)
       namespaceMgr.AddNamespace("b", "http://example.books.ru")
       For Each node As XPathNavigator In nav.Select( _
               "//b:book[not(b:price[. > 10.00])]/b:price", namespaceMgr)
           Dim price As Decimal = _
               CType(node.ValueAs(GetType(Decimal)), Decimal)
           Response.Write(String.Format("Price is {0}
", _ price)) Next
   End Sub

End Class File: Data.xml <?xml version="1.0"?> <bookstore xmlns="http://example.books.ru"

          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <book genre="A" 
         publicationdate="1981" 
         ISBN="1-11111-11-0">
       <title>title 1</title>
       <author>
           <first-name>A</first-name>
           <last-name>B</last-name>
       </author>
       <price>8</price>
   </book>
   <book genre="B" 
         publicationdate="1999" 
         ISBN="0-222-22222-2">
       <title>title 2</title>
       <author>
           <first-name>C</first-name>
           <last-name>D</last-name>
       </author>
       <price>11.99</price>
   </book>

</bookstore></source>


Use XPath to navigate XML document (VB.net)

   <source lang="csharp">

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

  sub Page_Load(Sender as object, e as EventArgs)
     Dim objReader as New XmlTextReader(Server.MapPath("Data.xml"))
     Dim objDoc as XPathDocument = new XPathDocument(objReader)
     Dim objNav as XPathNavigator = objDoc.CreateNavigator()
     DisplayNode(objNav)
  end sub
  sub DisplayNode(objNav as XPathNavigator)
     If objNav.HasChildren then
        objNav.MoveToFirstChild()
        Format(objNav)
        DisplayNode(objNav)
        objNav.MoveToParent()
     End If
     While objNav.MoveToNext()
        Format(objNav)
        DisplayNode(objNav)
     end While
  end sub
  Private Sub Format(objNav As XPathNavigator)
     If Not objNav.HasChildren then
        if objNav.NodeType <> XmlNodeType.Text then
           Response.Write("<" & _
              objNav.Name & ">")
        end if
        Response.Write(" - " & objNav.Value & _
              "
" & vbCrLf) Else Dim i As Integer Response.Write("<" & objNav.Name & _ ">" & vbCrLf) If objNav.HasAttributes then Response.Write("
Attributes of <" & _ objNav.Name & ">
" & vbCrLf) End If while objNav.MoveToNextAttribute() Response.Write("<" & objNav.Name & "> " & objNav.Value & " ") end while Response.Write("
" & vbCrLf) End If end sub

</script> <html><body> </body></html></source>


Use XPath to query XML data (VB.net)

   <source lang="csharp">

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

  sub SelectData(Sender as Object, e as EventArgs)
     Dim objReader as New XmlTextReader(Server.MapPath("Data.xml"))
     Dim objDoc as XPathDocument = new XPathDocument(objReader)
     Dim objNav as XPathNavigator = objDoc.CreateNavigator()
     try
        Dim expr as XPathExpression = objNav.rupile(tbQuery.Text)
        Dim mngr as XmlNamespaceManager = new XmlNamespaceManager(objReader.NameTable)
        mngr.AddNamespace("","x-schema:books.xdr")
        expr.SetContext(mngr)
        dim objIterator as XPathNodeIterator = objNav.Select(expr)
        While objIterator.MoveNext()
           Format(objIterator.Current)
        end while
     catch ex As Exception
        Response.Write(ex.Message)
     end try
     objReader.Close()
  end sub
  Private Sub Format(objNav As XPathNavigator)
     Dim strValue As String
     Dim strName As String
     If objNav.HasChildren then
        strName = objNav.Name
        objNav.MoveToFirstChild()
        strValue = objNav.Value
     Else 
        strValue = objNav.Value
        strName = objNav.Name
     End If
     Response.Write("<" & strName & _
        ">" & strValue & "
") End Sub

</script> <html><body>

  <form runat=server>
     <asp:Textbox id="tbQuery" runat=server/>
     <asp:Button id="btnSubmit" text="Submit" 
        runat=server OnClick="SelectData"/>
</form>

</body></html> File: Data.xml <?xml version="1.0"?> <bookstore>

 <book genre="asdf">
   <title>asdf</title>
   <author>
     <first-name>asdf</first-name>
     <last-name>asdf</last-name>
   </author>
   <price>asdf</price>
 </book>
 <book genre="asdf">
   <title>asdf</title>
   <author>
     <first-name>asdf</first-name>
     <last-name>asdf</last-name>
   </author>
   <price>asdf</price>
 </book>
 <book genre="asdf">
   <title>asdf</title>
   <author>
     <first-name>asdf</first-name>
     <last-name>asdf</last-name>
   </author>
   <price>asdf</price>
 </book>

</bookstore></source>


XPath Navigator Read

   <source lang="csharp">

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="XPathNavigatorRead" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

   <title>Untitled Page</title>

</head> <body>

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

</body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Xml; using System.Xml.XPath; using System.Text; public partial class XPathNavigatorRead : System.Web.UI.Page {

   protected void Page_Load(object sender, EventArgs e)
   {
   string xmlFile = Server.MapPath("Data.xml");
   XmlDocument doc = new XmlDocument();
   doc.Load(xmlFile);
   XPathNavigator xnav = doc.CreateNavigator();
   XmlText.Text = GetXNavDescr(xnav, 0);
   }
 private string GetXNavDescr(XPathNavigator xnav, int level)
 {
   string indent = "";
   for (int i = 0; i < level; i++)
     indent += "     ";
   StringBuilder str = new StringBuilder("");
   switch (xnav.NodeType)
   {
     case XPathNodeType.Root:
       str.Append("ROOT");
       str.Append("
"); break; case XPathNodeType.Element: str.Append(indent); str.Append("Element: "); str.Append(xnav.Name); str.Append("
"); break; case XPathNodeType.Text: str.Append(indent); str.Append(" - Value: "); str.Append(xnav.Value); str.Append("
"); break; case XPathNodeType.rument: str.Append(indent); str.Append("Comment: "); str.Append(xnav.Value); str.Append("
"); break; } if (xnav.HasAttributes) { xnav.MoveToFirstAttribute(); do { str.Append(indent); str.Append(" - Attribute: "); str.Append(xnav.Name); str.Append(" Value: "); str.Append(xnav.Value); str.Append("
"); } while (xnav.MoveToNextAttribute()); xnav.MoveToParent(); } if (xnav.HasChildren) { xnav.MoveToFirstChild(); do { str.Append(GetXNavDescr(xnav, level + 1)); } while (xnav.MoveToNext()); xnav.MoveToParent(); } return str.ToString(); }

} File: Data.xml <?xml version="1.0"?> <DvdList>

  <DVD ID="1" Category="Category 1">
     <Title>title 1</Title>
     <Director>directory 2</Director>
     <Price>1</Price>
     <Starring>
        <Star>star 1</Star>
        <Star>star 2</Star>
     </Starring>
  </DVD>
  <DVD ID="2" Category="Category 2">
     <Title>title 2</Title>
     <Director>directory 2</Director>
     <Price>2</Price>
     <Starring>
        <Star>star 3</Star>
        <Star>star 4</Star>
     </Starring>
  </DVD>

</DvdList></source>


XPath Search

   <source lang="csharp">

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="XPathSearch" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

   <title>Untitled Page</title>

</head> <body>

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

</body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Xml; using System.Text; public partial class XPathSearch : System.Web.UI.Page {

   protected void Page_Load(object sender, EventArgs e)
   {
   string xmlFile = Server.MapPath("Data.xml");
   XmlDocument doc = new XmlDocument();
   doc.Load(xmlFile);
   XmlNodeList nodes = doc.SelectNodes("/DvdList/DVD/Title[../@Category="Category 1"]");
   StringBuilder str = new StringBuilder();
   foreach (XmlNode node in nodes)
   {
     str.Append("Found: ");
     str.Append(node.ChildNodes[0].Value);
     str.Append("
"); } XmlText.Text = str.ToString(); }

} File: Data.xml <?xml version="1.0"?> <DvdList>

  <DVD ID="1" Category="Category 1">
     <Title>title 1</Title>
     <Director>directory 2</Director>
     <Price>1</Price>
     <Starring>
        <Star>star 1</Star>
        <Star>star 2</Star>
     </Starring>
  </DVD>
  <DVD ID="2" Category="Category 2">
     <Title>title 2</Title>
     <Director>directory 2</Director>
     <Price>2</Price>
     <Starring>
        <Star>star 3</Star>
        <Star>star 4</Star>
     </Starring>
  </DVD>

</DvdList></source>