亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

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
安福县| 漠河县| 保定市| 佳木斯市| 台南县| 乌恰县| 泸西县| 澄迈县| 白河县| 虎林市| 含山县| 长兴县| 乌拉特中旗| 长汀县| 盐山县| 咸宁市| 大安市| 景洪市| 晋州市| 武平县| 佛学| 全南县| 白水县| 温宿县| 宁波市| 青阳县| 金门县| 栾川县| 神农架林区| 萨迦县| 平凉市| 措勤县| 恩平市| 吉林省| 罗城| 新化县| 于都县| 县级市| 资溪县| 吕梁市| 辉南县|