zoukankan      html  css  js  c++  java
  • C# 通过XPath查询/搜索/查找XML

    //实例:查找所有书名包含Harry的书

    bookdemo.xml
    <?xml version="1.0" encoding="utf-8" ?>

    <bookstore>



    <book category="COOKING">

    <title lang="en">Everyday Italian</title>

    <author>Giada De Laurentiis</author>

    <year>2005</year>

    <price>30.00</price>

    </book>



    <book category="CHILDREN">

    <title lang="en">Harry Potter</title>

    <author>J K. Rowling</author>

    <year>2005</year>

    <price>29.99</price>

    </book>



    <book category="WEB">

    <title lang="en">XQuery Kick Start</title>

    <author>James McGovern</author>

    <author>Per Bothner</author>

    <author>Kurt Cagle</author>

    <author>James Linn</author>

    <author>Vaidyanathan Nagarajan</author>

    <year>2003</year>

    <price>49.99</price>

    </book>



    <book category="WEB">

    <title lang="en">Learning XML</title>

    <author>Erik T. Ray</author>

    <year>2003</year>

    <price>39.95</price>

    </book>



    </bookstore>

    .cs

    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.XPath;

    //通过XPath查询XML,在XPath中使用函数 
    publicpartialclass _Default : System.Web.UI.Page
    {
    public String contx;
    protectedvoid Page_Load(object sender, EventArgs e)
    {
    contx
    ="";
    XPathNavigator nav;
    XPathDocument docNav;
    //XPathNodeIterator NodeIter; 
    XPathNavigator node;
    String strExpression;

    try
    {
    docNav
    =new XPathDocument(System.AppDomain.CurrentDomain.BaseDirectory +"bookdemo.xml");
    nav
    = docNav.CreateNavigator();
    strExpression
    ="/bookstore/book[contains(title/text(), 'Harry')]/title";
    node
    = nav.SelectSingleNode(strExpression);
    contx
    += node.InnerXml;

    /*
    NodeIter = nav.Select(strExpression);
    while (NodeIter.MoveNext())
    {
    contx += NodeIter.Current.Value + "<br />";
    }
    */
    }
    catch (Exception)
    {
    contx
    ="Unfind !";
    }
    }
    }

    (注释部分为查询全部节点的方法)

  • 相关阅读:
    运算符
    JS的基本概念和数据类型
    开源基于Canal的开源增量数据订阅&消费中间件
    用AntDeploy如何更新Agent
    AntDeploy发布前端项目到IIS(脱离vs单独使用)
    截图上传录屏gif上传工具推荐
    netcore开发windows普通服务(非Web)并一键发布到服务器
    一键发布部署vs插件[AntDeploy]开源了
    基于python的Elasticsearch索引的建立和数据的上传
    浅谈闭包
  • 原文地址:https://www.cnblogs.com/bloodmage/p/1940873.html
Copyright © 2011-2022 走看看