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}"); }
运行结果
代码执行后输出完全匹配预期的表格效果:
| Intent | Sample |
|---|---|
| Unassigned | cancel |
| BUSINESS_PAY | make payment |
内容的提问来源于stack exchange,提问作者aarong_
相关产品推荐
相关产品推荐

