虎克的博客

Enthusiasm Biogeography-Biodiversity Informatics-Data Sciences

调用XPath显示XML文档

| Comments

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Schema;

public partial class ShowXpath : System.Web.UI.Page
{
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!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();
        }

    }
    /// <summary>
    /// Handles the SelectedIndexChanged event of the ddlExpressions control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void ddlExpressions_SelectedIndexChanged(object sender, EventArgs e)
    {
        UpdateDisplay();
    }
    /// <summary>
    /// Updates the display.
    /// </summary>
    void UpdateDisplay()
    {
        lstOutput.Items.Clear();
        string xmlFilePath = Request.PhysicalApplicationPath + @"App_Data\Books.xml";
        XmlDocument doc = new XmlDocument();
        doc.Load(xmlFilePath);
        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);
        }
 
    }
}

Comments