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

如何在C#中从指定XML文件提取单个值并转换为字符串?

C# 提取XML指定字段值的解决方案

你的问题出在对XML节点结构的理解上:XML里并没有名为Rating/Filename的直接节点,这些是Field节点的Name属性值,所以之前的查询方式无法匹配到目标内容。以下是两种可行的解决方法:

方法一:使用XDocument(推荐,更灵活)

基于你已加载的XDocument实例,通过匹配Field节点的Name属性来提取对应值:

var document = XDocument.Load(@"F:\test\2 Guns.xml");

// 提取Filename
string filename = document.Descendants("Field")
    .First(field => field.Attribute("Name").Value == "Filename")
    .Value;

// 提取Rating
string rating = document.Descendants("Field")
    .First(field => field.Attribute("Name").Value == "Rating")
    .Value;

// 提取Genre
string genre = document.Descendants("Field")
    .First(field => field.Attribute("Name").Value == "Genre")
    .Value;

如果担心字段不存在导致报错,可以用FirstOrDefault()替代First(),并添加空值判断逻辑。

方法二:修正DataSet的使用方式

DataSet解析该XML时,会生成Field表存储所有字段的Name和Value,你可以直接查询这个表:

DataSet ds = new DataSet();
ds.ReadXml(@"F:\test\2 Guns.xml");

// 提取Filename
string filename = ds.Tables["Field"].AsEnumerable()
    .Where(row => row["Name"].ToString() == "Filename")
    .Select(row => row["Value"].ToString())
    .FirstOrDefault();

// 提取Rating
string rating = ds.Tables["Field"].AsEnumerable()
    .Where(row => row["Name"].ToString() == "Rating")
    .Select(row => row["Value"].ToString())
    .FirstOrDefault();

// 提取Genre
string genre = ds.Tables["Field"].AsEnumerable()
    .Where(row => row["Name"].ToString() == "Genre")
    .Select(row => row["Value"].ToString())
    .FirstOrDefault();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:52:51