Using the XPathNavigator for Navigating Xml Documents : XPath « XML « ASP.Net






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>

 








Related examples in the same category

1.Use XPath to read XML document
2.XPathNavigator Selection Example
3.Use XML Path to locate Node and edit its value
4.Use XPathNavigator to create attribute
5.Finding a Particular Node in an XML Document?
6.Finding a Particular Node in an XML Document (VB)