C# 如何只读取xml的某个片段

来源:这里教程网 时间:2026-02-21 17:29:36 作者:

在 C# 中,若只想读取 XML 的某个特定片段(例如某个节点或节点集合),可以使用 XmlDocumentXDocument(LINQ to XML)来实现。推荐使用 XDocument,因为它更简洁、现代。

使用 XDocument 读取指定节点片段

假设你有如下 XML 文件:

<?xml version="1.0" encoding="utf-8"?>

  
    Alice
    25
  

  
    Bob
    30
  

你想只读取 Id 为 "2" 的 Person 节点内容。

示例代码:

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

class Program
{
  static void Main()
  {
    string xml = @"
      Alice25
      Bob30
    
";

    XDocument doc = XDocument.Parse(xml);

    // 查找 Id 为 2 的 Person 节点
    var targetPerson = doc.Root
      .Elements("Person")
      .FirstOrDefault(e => e.Attribute("Id")?.Value == "2");

    if (targetPerson != null)
    {
      Console.WriteLine(targetPerson); // 输出整个节点
      // 也可以单独读取子元素
      Console.WriteLine($"Name: {targetPerson.Element("Name")?.Value}");
      Console.WriteLine($"Age: {targetPerson.Element("Age")?.Value}");
    }
  }
}

从文件加载 XML 并读取片段

如果 XML 存在于文件中,只需将

XDocument.Parse
替换为
XDocument.Load("path/to/file.xml")

XDocument doc = XDocument.Load("data.xml");
var node = doc.Root.Elements("Person")
             .FirstOrDefault(e => e.Attribute("Id")?.Value == "2");

使用 XPath(可选,需添加命名空间)

你也可以使用 XPath 表达式来定位节点,但需要引入 System.Xml.XPath

using System.Xml.XPath;

var node = doc.XPathSelectElement("//Person[@Id='2']");

注意事项

确保节点和属性存在,避免空引用异常,建议使用 ?. 操作符 若 XML 结构复杂或嵌套深,XPath 可能更方便 XDocument 适合小到中等大小的 XML;超大文件建议用 XmlReader 流式处理

基本上就这些。用 LINQ to XML(XDocument)方式最直观,筛选条件灵活,代码也清晰。

相关推荐