ASP.Net Code

ASP.Net: Parse an XML Document Using XPath

You can user Xpath queries in ASP.Net to select only the content you want from an XML document. In this case I got the XML list of articles from ASPFree.com


<%@ Page Language="VB" %>
<%@ import Namespace="System.XML" %>
<%@ import Namespace="System.XML.XPath" %>
<%@ import Namespace="System.XML.Xsl" %>
<script runat="server">

    'protected withEvents lstTitles as new ListBox
   
    Sub Page_Load(Src As Object, E As EventArgs)
         If Not IsPostBack Then
            showNames()
         End If
   
    End Sub
   
    Sub Shownames()
         Dim Doc as New XPathDocument(Server.MapPath("aspfree.xml"))
         dim myNav as XPathNavigator
         myNav = Doc.CreateNavigator ()
   
         dim myItr as XPathNodeIterator
         'myItr = myNav.Select("descendant::title")
         myItr = myNav.Select("/rss/channel/item/title")
   
         While ( myItr.MoveNext () )
             lstTitles.Items.Add( myItr.Current.Value )
         End While
   
     End Sub
   
     Private Sub ShowURL(S As Object, E As EventArgs)' handles lstTitles.SelectedIndexChanged
         dim title as String = lstTitles.SelectedItem.Text.Trim()
   
         dim aDoc as New XPathDocument(Server.MapPath("aspfree.xml"))
         dim myNav as XPathNavigator
         myNav = aDoc.CreateNavigator()
   
         dim myItr as XPathNodeIterator
         myItr = myNav.Select("descendant::item[title='"+title+"']/link")
         'myItr = myNav.Select("/rss/channel/item[title='"+title+"']/link")
         myItr.MoveNext ()
         url.Text = myItr.Current.Value
   
     End Sub

</script>
<?xml version="1.0" encoding="iso-8859-1"?>
<!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>
    <title>XPathNavigator</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
    <form runat="server">
        <asp:ListBox id="lstTitles" runat="server" AutoPostBack="false"></asp:ListBox>
        <br />
        <asp:Button id="Button1" onclick="showURL" runat="server" Text="get url"></asp:Button>
        <asp:TextBox id="url" runat="server" Width="400px"></asp:TextBox>
    </form>
</body>
</html>
Share

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image