中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

c# xpath案例分析

c#
小樊
82
2024-09-19 19:58:28
欄目: 編程語言

在C#中,使用System.Xml.XPath命名空間可以方便地處理XPath表達式

假設我們有以下XML文檔:

<?xml version="1.0" encoding="UTF-8"?>
<books>
  <book id="1">
    <title>Book 1</title>
    <author>Author 1</author>
  </book>
  <book id="2">
    <title>Book 2</title>
    <author>Author 2</author>
  </book>
  <book id="3">
    <title>Book 3</title>
    <author>Author 3</author>
  </book>
</books>

現在,我們將使用C#和XPath表達式來查詢此XML文檔。

  1. 選擇所有書籍的標題:
using System;
using System.Xml;
using System.Xml.XPath;

class XPathExample
{
    static void Main()
    {
        string xml = @"
          <books>
            <book id='1'>
              <title>Book 1</title>
              <author>Author 1</author>
            </book>
            <book id='2'>
              <title>Book 2</title>
              <author>Author 2</author>
            </book>
            <book id='3'>
              <title>Book 3</title>
              <author>Author 3</author>
            </book>
          </books>";

        XPathDocument doc = new XPathDocument(xml);
        XPathNavigator navigator = doc.CreateNavigator();

        XPathExpression expr = navigator.Compile("//title");
        XPathNodeIterator iterator = expr.Select();

        Console.WriteLine("Book titles:");
        while (iterator.MoveNext())
        {
            Console.WriteLine(iterator.Current.Value);
        }
    }
}

輸出:

Book titles:
Book 1
Book 2
Book 3
  1. 根據書籍ID選擇書籍:
using System;
using System.Xml;
using System.Xml.XPath;

class XPathExample
{
    static void Main()
    {
        string xml = @"
          <books>
            <book id='1'>
              <title>Book 1</title>
              <author>Author 1</author>
            </book>
            <book id='2'>
              <title>Book 2</title>
              <author>Author 2</author>
            </book>
            <book id='3'>
              <title>Book 3</title>
              <author>Author 3</author>
            </book>
          </books>";

        XPathDocument doc = new XPathDocument(xml);
        XPathNavigator navigator = doc.CreateNavigator();

        XPathExpression expr = navigator.Compile("//book[@id='2']");
        XPathNodeIterator iterator = expr.Select();

        Console.WriteLine("Book with ID 2:");
        while (iterator.MoveNext())
        {
            Console.WriteLine(iterator.Current.Value);
        }
    }
}

輸出:

Book with ID 2:
Book 2
Author 2

這些示例展示了如何使用C#和XPath表達式查詢XML文檔。您可以根據需要修改這些示例以滿足您的實際需求。

0
阿坝| 阿鲁科尔沁旗| 新安县| 宜丰县| 永吉县| 晋城| 醴陵市| 阳谷县| 庆城县| 开江县| 上虞市| 清新县| 榆社县| 浮梁县| 隆昌县| 蓬溪县| 资讯| 鸡西市| 郎溪县| 绵阳市| 古浪县| 开远市| 瓮安县| 宜良县| 丹寨县| 遵义市| 当阳市| 邓州市| 唐山市| 仁寿县| 商丘市| 外汇| 旬邑县| 三门峡市| 九台市| 太白县| 丹江口市| 双辽市| 隆子县| 河曲县| 六枝特区|