c#通过xpath读取xml示例

时间:2023-07-16 01:31:05 

需要修改Main方法第一行代码的路径为你的books.xml文件绝对路径或相对路径。代码演示了XPath各种语法的使用情况

books.xml


<?xml version="1.0" encoding="ISO-8859-1"?>
<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>

主程序


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace XmlProcessTest
{
    public class Program
    {
        /// <summary>
        /// 加载XML文件
        /// </summary>
        /// <param name="xmlFilePath">XML文件路径</param>
        /// <returns></returns>
        public static XmlDocument LoadXmlDoc(string xmlFilePath)
        {
            var xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlFilePath);

            return xmlDoc;
        }

        /// <summary>
        /// 根据指定的XPath表达式获取XML结点列表
        /// </summary>
        /// <param name="xmlDoc"></param>
        /// <param name="xpathExpr"></param>
        /// <returns></returns>
        public static XmlNodeList GetXmlNodes(XmlDocument xmlDoc, string xpathExpr)
        {
            if (xmlDoc == null)
                return null;

            return xmlDoc.SelectNodes(xpathExpr);
        }

        public static string GetXmlNodeInfo(XmlNode node, string type="xml")
        {
            if (node == null)
                return "Empty node or error node";

            string xmlNodeInfo = null;
            switch (type)
            {
                case "text":
                    xmlNodeInfo = node.InnerText;
                    break;
                default:
                    xmlNodeInfo = node.InnerXml;
                    break;
            }

            return xmlNodeInfo;
        }

        public static void Main(string[] args)
        {
            var xmlDoc = LoadXmlDoc(@"你的books.xml文件路径");

            var rootExpr = "/bookstore";   //  根节点对应的XPath表达式
            var rootNode = GetXmlNodes(xmlDoc, rootExpr);   //
            Console.WriteLine("XPath表达式为 /bookstore,根节点bookstore的所有子节点XML内容如下:");
            Console.WriteLine(GetXmlNodeInfo(rootNode[0]));

            Console.WriteLine();

            var allBooksExpr = "/bookstore/book"; // 根节点bookstore的子元素的所有子节点
            var bookNodes = GetXmlNodes(xmlDoc, allBooksExpr);
            Console.WriteLine("XPath表达式为 bookstore/book,book节点共有:" + bookNodes.Count);

            Console.WriteLine();

            var anyBookExpr = "//book"; // 选取所有book子元素,而不管它们在文档中的位置
            var anyBookNodes = GetXmlNodes(xmlDoc, anyBookExpr);
            Console.WriteLine("XPath表达式为 //book,book节点共有:" + anyBookNodes.Count);
            Console.WriteLine(anyBookNodes[0].InnerXml);
            Console.WriteLine(anyBookNodes[0].OuterXml);

            Console.WriteLine();

            var categoryExpr = "//@category";   // 选取名为category的所有属性
            var allCategoryNodes = GetXmlNodes(xmlDoc, categoryExpr);
            Console.WriteLine("XPath表达式为 //@category,category节点共有:" + allCategoryNodes.Count);
            Console.WriteLine(allCategoryNodes[0].InnerText);
            Console.WriteLine(allCategoryNodes[0].InnerXml);

            Console.WriteLine();

            var titleWithLangExpr = "//title[@lang]";   // 选取所有带有lang属性的title节点
            var titleWithLangNodes = GetXmlNodes(xmlDoc, titleWithLangExpr);
            Console.WriteLine("XPath表达式为 //title[@lang],带lang属性的title节点共有:" + titleWithLangNodes.Count);
            Console.WriteLine(GetXmlNodeInfo(titleWithLangNodes[0]));

            var englishTitleExpr = "//title[@lang='en']";   // 选取所有lang属性值为en的title节点
            var englishTitleNodes = GetXmlNodes(xmlDoc, englishTitleExpr);
            Console.WriteLine("XPath表达式为 //title[@lang='en'],lang属性值为en的title节点共有:" + englishTitleNodes.Count);
            Console.WriteLine(GetXmlNodeInfo(englishTitleNodes[0]));

            Console.WriteLine();

            // 使用索引的XPath查询
            var indexExpr = "/bookstore/book[1]";   // 取bookstore子元素的第一个book元素
            var firstBookNode = GetXmlNodes(xmlDoc, indexExpr);
            Console.WriteLine("XPath表达式为 /bookstore/book[1],节点数为:" + firstBookNode.Count);
            Console.WriteLine(GetXmlNodeInfo(firstBookNode[0]));

            Console.WriteLine();

            var indexExpr2 = "/bookstore/book[last()]"; // 取bookstore子元素的最后一个book元素
            var lastBookNode = GetXmlNodes(xmlDoc, indexExpr2);
            Console.WriteLine("XPath表达式为 /bookstore/book[last()],节点数为:" + lastBookNode.Count);
            Console.WriteLine(GetXmlNodeInfo(lastBookNode[0]));

            Console.WriteLine();

            var indexExpr3 = "/bookstore/book[last()-1]"; // 取bookstore子元素的倒数第二个book元素
            var nextByLastBookNode = GetXmlNodes(xmlDoc, indexExpr3);
            Console.WriteLine("XPath表达式为 /bookstore/book[last()-1],节点数为:" + lastBookNode.Count);
            Console.WriteLine(GetXmlNodeInfo(nextByLastBookNode[0]));

            Console.WriteLine();

            var indexExpr4 = "/bookstore/book[position()<3]"; // 取bookstore的前两个book子元素
            var firstTwoBookNodes = GetXmlNodes(xmlDoc, indexExpr4);
            Console.WriteLine("XPath表达式为 /bookstore/book[position()<3],节点数为:" + firstTwoBookNodes.Count);
            Console.WriteLine(GetXmlNodeInfo(firstTwoBookNodes[0]));

            Console.WriteLine();

            // 带属性值过滤条件的XPath表达式
            var fileterExpr = "/bookstore/book[price>35.00]";   // 选取bookstore的所有price属性值大于35.00的book元素
            var bookGt35Nodes = GetXmlNodes(xmlDoc, fileterExpr);
            Console.WriteLine("XPath表达式为 /bookstore/book[price>35.00],节点数为:" + bookGt35Nodes.Count);
            Console.WriteLine(GetXmlNodeInfo(bookGt35Nodes[0]));

            // 通配符
            // @*                匹配任何属性节点
            // node()             匹配任何类型的节点
            // /bookstore/*   选取 bookstore 元素的所有子元素
            // //*                   选取文档的所有元素
            // //title[@*]        选取所有带有属性的 title 元素
            var allTitleWithAttrExpr = "//title[@*]";
            var allTitleWithAttrNodes = GetXmlNodes(xmlDoc, allTitleWithAttrExpr);
            Console.WriteLine("XPath表达式为 title[@*],节点数为:" + allTitleWithAttrNodes.Count);
            Console.WriteLine(GetXmlNodeInfo(allTitleWithAttrNodes[0]));

            Console.WriteLine();

            // |        或
            var titleAndPriceExpr = "//book/title | //book/price";
            var titleAndPriceNodes = GetXmlNodes(xmlDoc, titleAndPriceExpr);
            Console.WriteLine("XPath表达式为 //book/title | //book/price,节点数为:" + titleAndPriceNodes.Count);
            Console.WriteLine(GetXmlNodeInfo(titleAndPriceNodes[0]));

            // text()  选取文本
            var titleTextExpr = "//title/text()";
            var titleTextNodes = GetXmlNodes(xmlDoc, titleTextExpr);
            Console.WriteLine("XPath表达式为 //title/text(),节点数为:" + titleTextNodes.Count);
            Console.WriteLine(titleTextNodes[0].Value); // 文本节点的值

            Console.ReadKey();
        }
    }
}

标签:c#,xpath,xml
0
投稿

猜你喜欢

  • SpringBoot上传文件到本服务器 目录与jar包同级问题

    2022-01-27 07:15:41
  • tk.mybatis实现uuid主键生成的示例代码

    2022-01-22 00:17:13
  • Springboot集成spring data elasticsearch过程详解

    2023-04-16 00:42:16
  • java模拟TCP通信实现客户端上传文件到服务器端

    2023-11-26 10:14:49
  • c#读取XML多级子节点

    2023-10-10 21:03:44
  • Java流式操作之Collectors工具类操作指南

    2022-12-01 01:25:55
  • .Net WInform开发笔记(五)关于事件Event

    2023-11-22 01:00:18
  • C# 使用WPF 用MediaElement控件实现视频循环播放

    2022-04-28 03:34:26
  • springboot集成shiro详细总结

    2022-07-12 14:56:17
  • Java 如何实现时间控制

    2023-02-20 06:19:23
  • 如何安装java的运行环境IDEA

    2022-09-20 10:42:38
  • java处理按钮点击事件的方法

    2021-08-24 16:28:10
  • Java网络编程UDP实现多线程在线聊天

    2022-01-08 21:48:32
  • Maven+Tomcat8 实现自动化部署的方法

    2023-01-03 06:44:20
  • Spring中事务传播行为的介绍

    2023-06-24 01:21:01
  • intellij idea如何将web项目打成war包的实现

    2023-05-27 23:12:27
  • java使用POI操作excel文件

    2023-05-17 00:37:12
  • Java Swing JComboBox下拉列表框的示例代码

    2022-09-16 00:24:50
  • Android通过startService实现文件批量下载

    2022-11-02 05:29:52
  • Android编程实现对电池状态的监视功能示例

    2023-11-16 08:40:03
  • asp之家 软件编程 m.aspxhome.com