如何在C#中根据CountryID读取XML中的英文国家名称
解决根据CountryID从XML中获取EnglishCountryName的问题
我一眼就看出问题出在你的XPath表达式和取值方式上,咱们一步步来修正:
问题分析
你的原代码里的XPath CountryCodeNames/CountryID="+natxmlcode+"/EnglishCountryName" 犯了两个关键错误:
- CountryID是属性不是子节点:XML里的
CountryID是<Country>元素的属性,不是它的子节点,所以不能用/CountryID这种写法,得用属性选择器@CountryID。 - EnglishCountryName也是属性:它同样是
<Country>的属性,不是节点的内部文本,所以不能用InnerText来获取,得通过属性集合来取值。
修正后的XmlDocument实现
下面是调整后的代码,还加了空值判断避免异常:
string natxmlcode = crdv4.smartcardData.NationalityCode.ToString(); XmlDocument xd = new XmlDocument(); string xmlpath = @"D:\CountriesNameList.xml"; xd.Load(xmlpath); // 正确的XPath:筛选CountryCodeNames下CountryID属性匹配的Country元素 XmlNode countryNode = xd.SelectSingleNode($"CountryCodeNames/Country[@CountryID='{natxmlcode}']"); string nationality; if (countryNode != null) { // 获取EnglishCountryName属性值,同时去除XML里多余的空格 nationality = countryNode.Attributes["EnglishCountryName"].Value.Trim(); } else { // 处理找不到对应ID的情况,用默认值 nationality = "NOT DEFINED"; }
更简洁的LINQ to XML实现
如果你愿意用更现代的方式,可以试试LINQ to XML,代码更简洁,空值处理也更优雅:
string natxmlcode = crdv4.smartcardData.NationalityCode.ToString(); string xmlpath = @"D:\CountriesNameList.xml"; XDocument xdoc = XDocument.Load(xmlpath); // 查找匹配CountryID的Country元素 var country = xdoc.Descendants("Country") .FirstOrDefault(c => c.Attribute("CountryID")?.Value == natxmlcode); // 链式获取属性值,空值时用默认值,同时去除空格 string nationality = country?.Attribute("EnglishCountryName")?.Value?.Trim() ?? "NOT DEFINED";
额外提示
- 注意你的XML里很多
EnglishCountryName后面带空格(比如"ALGERIA "),用Trim()可以清理这些多余的空白字符。 - 确保XML文件路径正确,如果是相对路径,要注意程序的工作目录,避免找不到文件的问题。
内容的提问来源于stack exchange,提问作者Sijo George Oommen
相关产品推荐
相关产品推荐

