91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

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
晋州市| 罗甸县| 永善县| 乐陵市| 剑河县| 澄江县| 措美县| 德庆县| 长垣县| 彭泽县| 蛟河市| 凤城市| 疏勒县| 黔南| 衡东县| 东辽县| 固原市| 远安县| 江源县| 新田县| 九龙城区| 玉林市| 特克斯县| 博兴县| 德保县| 碌曲县| 云和县| 龙泉市| 高密市| 那坡县| 徐闻县| 广东省| 磐安县| 神池县| 桃园市| 波密县| 沈丘县| 沛县| 石景山区| 台江县| 龙岩市|