ASP.Net/XML/XPath

Материал из .Net Framework эксперт
Версия от 11:51, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Finding a Particular Node in an XML Document?

<%@ 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><br/>
      <asp:button id="LoadButton" runat="server" Text="Load XML Document" OnClick="LoadButton_Click"></asp:button><br/>
      <asp:TextBox id="ResultText" runat="server" Width="379px" Height="194px" TextMode="MultiLine"></asp:TextBox><br/>
      <asp:Button id="QueryButton" runat="server" Text="Query" OnClick="QueryButton_Click"></asp:Button><br/>
      <asp:TextBox id="XPathText" runat="server" Width="379px"></asp:TextBox><br/>
      <asp:TextBox id="QueryResult" runat="server" TextMode="MultiLine" Height="229px" Width="379"></asp:TextBox>
    </form>
  </body>
</HTML>



Finding a Particular Node in an XML Document (VB)

<%@ 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><br/>
      <asp:button id="LoadButton" runat="server" Text="Load XML Document" OnClick="LoadButton_Click"></asp:button><br/>
      <asp:TextBox id="ResultText" runat="server" Width="379px" Height="194px" TextMode="MultiLine"></asp:TextBox><br/>
      <asp:Button id="QueryButton" runat="server" Text="Query" OnClick="QueryButton_Click"></asp:Button><br/>
      <asp:TextBox id="XPathText" runat="server" Width="379px"></asp:TextBox><br/>
      <asp:TextBox id="QueryResult" runat="server" TextMode="MultiLine" Height="229px" Width="379"></asp:TextBox>
    </form>
  </body>
</HTML>



Use XML Path to locate Node and edit its value

<%--
Code Revised from
       
Professional ASP.NET 2.0 XML (Programmer to Programmer) (Paperback)
by Thiru Thangarathinam 
# Publisher: Wrox (January 18, 2006)
# Language: English
# 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>



Use XPathNavigator to create attribute

<%--
Code Revised from
       
Professional ASP.NET 2.0 XML (Programmer to Programmer) (Paperback)
by Thiru Thangarathinam 
# Publisher: Wrox (January 18, 2006)
# Language: English
# 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>



Use XPath to read XML document

<%--
Code Revised from
       
Professional ASP.NET 2.0 XML (Programmer to Programmer) (Paperback)
by Thiru Thangarathinam 
# Publisher: Wrox (January 18, 2006)
# Language: English
# 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">
    <div>
        Select the XPath Expression:
        <asp:DropDownList ID="ddlExpressions" AutoPostBack="true" runat="server" Width="410px" OnSelectedIndexChanged="ddlExpressions_SelectedIndexChanged">
        </asp:DropDownList>    
        <br />
        <br />
        <asp:ListBox ID="lstOutput" runat="server" Width="587px" Height="168px"></asp:ListBox>
    </div>
    </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>

--%>



Using the XPathNavigator for Navigating Xml Documents

<%@ 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 = "&nbsp;&nbsp;";
        String space3 = "&nbsp;&nbsp;&nbsp;";
    
        XmlDocument _XmlDoc = new XmlDocument();
        _XmlDoc.Load(Server.MapPath("Data.xml"));
    
        XPathNavigator _Nav;
        _Nav = _XmlDoc.CreateNavigator();
    
        _Nav.MoveToRoot();
        sb.Append("<B>Root: </B>");
        sb.Append("name=" + _Nav.Name + ", type=" + _Nav.NodeType.ToString());
        sb.Append("<BR/><BR/>");
        
        _Nav.MoveToFirstChild();
        sb.Append("name=" + _Nav.Name + ", type=" + _Nav.NodeType.ToString());
        sb.Append("<BR/>");
        
        _Nav.MoveToFirstChild();
        do 
        {
            sb.Append(space2);
            sb.Append("name=" + _Nav.Name + ", type=" + _Nav.NodeType.ToString());
            sb.Append("<BR/>");
        
            _Nav.MoveToFirstAttribute();
            sb.Append(space2);
            sb.Append("Attribute: " + _Nav.Name + "=" + _Nav.Value);
            sb.Append("<BR/>");
        
            _Nav.MoveToParent();
        
            _Nav.MoveToFirstChild();
            do
            {
                sb.Append(space3);
                sb.Append("name=" + _Nav.Name + ", type=" + _Nav.NodeType.ToString() + ", value=" + _Nav.Value);
                sb.Append("<BR/>");
            }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">
        <!-- Insert content here -->
        <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>



XPathNavigator Selection Example

<%--
Code Revised from
       
Professional ASP.NET 2.0 XML (Programmer to Programmer) (Paperback)
by Thiru Thangarathinam 
# Publisher: Wrox (January 18, 2006)
# Language: English
# 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">
    <div>
        Select the XPath Expression:
        <asp:DropDownList ID="ddlExpressions" AutoPostBack="true" runat="server" Width="410px" OnSelectedIndexChanged="ddlExpressions_SelectedIndexChanged">
        </asp:DropDownList>    
        <br />
        <br />
        <asp:ListBox ID="lstOutput" runat="server" Width="587px" Height="168px"></asp:ListBox>
    </div>
    </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>

--%>