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

如何从StreamReader读取的XML文件中获取sxnum属性值?

获取XML文件中sxnum属性的值

问题描述

当前使用StreamReader逐行读取XML文件,希望提取cd元素的sxnum属性值,现有代码如下:

using (StreamReader streamreader = new StreamReader(inputxmlfile))
{
    string doc = streamreader.ReadLine();
    while (doc != null)
    {
        if (content.Contains("sxnum")) // 注意:原代码中content变量未定义,应改为doc.Contains("sxnum")
        {
            // How to get the 'sxnum' attribute value?
        }
        doc = streamreader.ReadLine();
    }
}

对应的XML片段:

<?xml version="1.0" encoding="UTF-8"?>
    <catalog>
    <cd nominee ="1 2 First" sxnum="63828910">
        <title company="Grammy" price="10.20">1999 Grammy Nominees</title>
        <artist all="type">Many</artist>
        <country>USA</country>
        .....
</catalog>

期望输出:63828910

解决方案

方式一:基于现有StreamReader的字符串提取(不推荐)

如果必须沿用逐行读取的逻辑,可通过正则表达式匹配属性值,避免手动截取字符串的不稳定问题:

using System.Text.RegularExpressions;
using (StreamReader streamreader = new StreamReader(inputxmlfile))
{
    string line = streamreader.ReadLine();
    while (line != null)
    {
        if (line.Contains("sxnum"))
        {
            // 匹配sxnum="值"格式,捕获引号内的内容
            Match match = Regex.Match(line, @"sxnum=""([^""]+)""");
            if (match.Success)
            {
                string sxnumValue = match.Groups[1].Value;
                Console.WriteLine(sxnumValue); // 输出63828910
                break; // 找到目标后退出循环,减少多余读取
            }
        }
        line = streamreader.ReadLine();
    }
}

注意:该方式依赖XML的格式化结构,若属性换行或格式变更可能失效,仅适合临时场景。

方式二:使用XML专用解析器(推荐)

专业处理XML应使用.NET内置的XML解析类,稳定性和可读性远高于字符串匹配,以下提供两种标准实现:

方法A:LINQ to XML(XDocument)

using System.Xml.Linq;

XDocument doc = XDocument.Load(inputxmlfile);
// 定位第一个cd元素并提取sxnum属性值
string sxnumValue = doc.Descendants("cd")
                       .FirstOrDefault()?
                       .Attribute("sxnum")?
                       .Value;
if (!string.IsNullOrEmpty(sxnumValue))
{
    Console.WriteLine(sxnumValue); // 输出63828910
}

方法B:XmlDocument

using System.Xml;

XmlDocument doc = new XmlDocument();
doc.Load(inputxmlfile);
XmlNode cdNode = doc.SelectSingleNode("//cd");
if (cdNode != null)
{
    string sxnumValue = cdNode.Attributes["sxnum"]?.Value;
    if (!string.IsNullOrEmpty(sxnumValue))
    {
        Console.WriteLine(sxnumValue); // 输出63828910
    }
}

这两种方式不依赖XML的格式化格式,即使属性位置变化、元素换行也能正确提取值,是处理XML的标准做法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 02:25:49