温馨提示×

如何在C#中查询XML数据

c#
小樊
81
2024-10-14 13:19:59
栏目: 编程语言

在C#中查询XML数据,你可以使用System.Xml命名空间中的类,如XDocumentXElement

  1. 首先,确保你的项目中已经引用了System.Xml命名空间。

  2. 使用XDocumentXElement类加载XML数据。

  3. 使用LINQ to XML查询语法来查询XML数据。

下面是一个简单的示例,说明如何在C#中查询XML数据:

假设你有以下XML数据:

<?xml version="1.0" encoding="utf-8"?>
<people>
  <person id="1">
    <name>Alice</name>
    <age>30</age>
  </person>
  <person id="2">
    <name>Bob</name>
    <age>25</age>
  </person>
  <person id="3">
    <name>Charlie</name>
    <age>22</age>
  </person>
</people>

要在C#中查询这些数据,你可以这样做:

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

class Program
{
    static void Main()
    {
        // 加载XML数据
        string xmlData = @"
        <?xml version=""1.0"" encoding=""utf-8""?>
        <people>
          <person id=""1"">
            <name>Alice</name>
            <age>30</age>
          </person>
          <person id=""2"">
            <name>Bob</name>
            <age>25</age>
          </person>
          <person id=""3"">
            <name>Charlie</name>
            <age>22</age>
          </person>
        </people>";

        XDocument xdoc = XDocument.Parse(xmlData);

        // 查询XML数据
        var query = from person in xdoc.Descendants("person")
                    where person.Attribute("id").Value == "2"
                    select person;

        foreach (var item in query)
        {
            Console.WriteLine($"Name: {item.Element("name").Value}, Age: {item.Element("age").Value}");
        }
    }
}

在这个示例中,我们首先加载了XML数据,然后使用LINQ to XML查询语法查找具有特定ID的<person>元素。最后,我们遍历查询结果并输出每个人的姓名和年龄。

0