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

C#遍历XML节点读取属性时,无对应属性如何设置默认值

问题原因

直接读取属性值抛出异常的核心原因是:不存在intentref属性的<sample>节点调用xn.Attributes["intentref"]时会返回null,直接访问null的Value属性就会触发空引用错误。

修改后代码

遍历节点时先判断目标属性是否存在,不存在则将Intent值设为Unassigned,同时读取节点内部文本作为Sample列内容即可:

string str = "<samples><sample>cancel</sample><sample intentref='BUSINESS_PAY'>make payment</sample></samples>";
XmlDocument xml = new XmlDocument();
xml.LoadXml(str);  

XmlNodeList xnList = xml.SelectNodes("/samples/sample");
// 打印表头
Console.WriteLine("Intent\t\tSample");
foreach (XmlNode xn in xnList)
{
    XmlAttribute intentAttr = xn.Attributes["intentref"];
    string intent = intentAttr != null ? intentAttr.Value : "Unassigned";
    string sampleContent = xn.InnerText;
    Console.WriteLine($"{intent}\t{sampleContent}");
}
运行结果

代码执行后输出完全匹配预期的表格效果:

IntentSample
Unassignedcancel
BUSINESS_PAYmake payment

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 21:30:42