You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中使用XmlReader读取XML属性及元素值的问题求助

C#读取XML指定内容的实现方案

先假设你的XML结构(符合需求的示例)

<Root>
  <Subject class="Math" grade="10" id="S001">
    <p name="conDN">A180</p>
    <p name="Code">C007</p>
    <p name="product">LaptopPro</p>
    <p name="serial">SN20240501</p>
    <p name="other">无关内容</p>
  </Subject>
</Root>

方法一:使用XmlDocument(传统DOM方式,适合新手理解节点结构)

using System;
using System.Xml;

class Program
{
    static void Main()
    {
        // 若读取本地文件,替换为 doc.Load("你的XML文件路径");
        string xmlContent = @"<Root>
  <Subject class=""Math"" grade=""10"" id=""S001"">
    <p name=""conDN"">A180</p>
    <p name=""Code"">C007</p>
    <p name=""product"">LaptopPro</p>
    <p name=""serial"">SN20240501</p>
    <p name=""other"">无关内容</p>
  </Subject>
</Root>";

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

        // 读取Subject元素的class、grade、id属性
        XmlNode subjectNode = doc.SelectSingleNode("//Subject");
        if (subjectNode != null)
        {
            string className = subjectNode.Attributes["class"]?.Value;
            string grade = subjectNode.Attributes["grade"]?.Value;
            string id = subjectNode.Attributes["id"]?.Value;

            Console.WriteLine("Subject信息:");
            Console.WriteLine($"class: {className}");
            Console.WriteLine($"grade: {grade}");
            Console.WriteLine($"id: {id}");
        }

        // 读取指定name属性的<p>元素文本
        string[] targetNames = { "conDN", "Code", "product", "serial" };
        foreach (string name in targetNames)
        {
            XmlNode pNode = doc.SelectSingleNode($"//p[@name='{name}']");
            if (pNode != null)
            {
                Console.WriteLine($"{name}: {pNode.InnerText}");
            }
            else
            {
                Console.WriteLine($"{name} 未找到");
            }
        }
    }
}

方法二:使用LINQ to XML(更简洁的现代写法)

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

class Program
{
    static void Main()
    {
        // 若读取本地文件,替换为 XDocument.Load("你的XML文件路径");
        string xmlContent = @"<Root>
  <Subject class=""Math"" grade=""10"" id=""S001"">
    <p name=""conDN"">A180</p>
    <p name=""Code"">C007</p>
    <p name=""product"">LaptopPro</p>
    <p name=""serial"">SN20240501</p>
    <p name=""other"">无关内容</p>
  </Subject>
</Root>";

        XDocument doc = XDocument.Parse(xmlContent);

        // 读取Subject属性
        var subject = doc.Descendants("Subject").FirstOrDefault();
        if (subject != null)
        {
            string className = subject.Attribute("class")?.Value;
            string grade = subject.Attribute("grade")?.Value;
            string id = subject.Attribute("id")?.Value;

            Console.WriteLine("Subject信息:");
            Console.WriteLine($"class: {className}");
            Console.WriteLine($"grade: {grade}");
            Console.WriteLine($"id: {id}");
        }

        // 读取指定name的<p>元素文本
        string[] targetNames = { "conDN", "Code", "product", "serial" };
        foreach (string name in targetNames)
        {
            var pElement = doc.Descendants("p").FirstOrDefault(p => p.Attribute("name")?.Value == name);
            if (pElement != null)
            {
                Console.WriteLine($"{name}: {pElement.Value}");
            }
            else
            {
                Console.WriteLine($"{name} 未找到");
            }
        }
    }
}

关键注意事项

  • 读取本地文件时,把LoadXml/Parse替换为Load方法,传入文件的完整路径。
  • 用?.运算符处理节点或属性不存在的情况,避免空引用异常。
  • XPath语法说明://表示搜索XML中任意层级的节点,[@name='xxx']表示匹配属性name值为xxx的元素。

内容的提问来源于stack exchange,提问作者ghee148

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 19:40:28