c#

c# xpath在哪使用

小樊
85
2024-09-19 19:49:26
栏目: 编程语言

在C#中,要使用XPath来查询XML文档,你需要使用System.XmlSystem.Xml.Linq命名空间中的类。以下是两种方法的示例:

方法1:使用System.Xml命名空间

using System;
using System.Xml;

class Program
{
    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>
            </books>";

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xml);

        XmlNodeList bookList = doc.SelectNodes("//book");

        foreach (XmlNode book in bookList)
        {
            Console.WriteLine("Book ID: " + book.Attributes["id"].Value);
            Console.WriteLine("Title: " + book.SelectSingleNode("title").InnerText);
            Console.WriteLine("Author: " + book.SelectSingleNode("author").InnerText);
            Console.WriteLine();
        }
    }
}

方法2:使用System.Xml.Linq命名空间

using System;
using System.Linq;
using System.Xml.Linq;

class Program
{
    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>
            </books>";

        XDocument doc = XDocument.Parse(xml);

        var bookList = doc.Descendants("book");

        foreach (var book in bookList)
        {
            Console.WriteLine("Book ID: " + book.Attribute("id").Value);
            Console.WriteLine("Title: " + book.Element("title").Value);
            Console.WriteLine("Author: " + book.Element("author").Value);
            Console.WriteLine();
        }
    }
}

在这两个示例中,我们首先创建了一个包含书籍信息的XML字符串。然后,我们分别使用XmlDocumentXDocument类加载XML字符串,并使用XPath查询(//book)来获取所有书籍节点。最后,我们遍历查询结果并输出书籍的ID、标题和作者。

0
看了该问题的人还看了