C#中如何使用Linq从XML提取properties、属性及BooleanValue值
修复方案
错误原因
你代码的核心错误有3处:
- 属性匹配错误:
<l7:Property>的key属性没有l7命名空间,且属性名为小写key,原代码错误使用带命名空间的大写Key匹配,无法命中属性直接返回null。 - 节点层级错误:
BooleanValue是Property节点的子节点,你直接在父级Properties节点下查找该节点,必然找不到。 - 遍历逻辑错误:你遍历的是
Properties节点集合(单个证书下仅有1个Properties节点),应该遍历Properties下的所有Property节点才能拿到全部属性。
修复后的代码
public static void GetPropertiesWithAttributes(XElement certNode, XNamespace ns) { // 先拿到当前证书的Properties节点 var propertiesNode = certNode.Element(ns + "Properties"); if (propertiesNode == null) return; // 遍历所有Property节点,需要筛选特定属性可以加where条件 var propertyList = from prop in propertiesNode.Elements(ns + "Property") select new { // 直接匹配无命名空间的小写key属性 PropertyKey = prop.Attribute("key")?.Value, // 拿当前Property下的BooleanValue值 BooleanValue = prop.Element(ns + "BooleanValue")?.Value }; // 输出结果 foreach (var item in propertyList) { Console.WriteLine($"属性名:{item.PropertyKey},值:{item.BooleanValue}"); } } // 如果要一次性提取所有证书的属性列表,可以用这个方法 public static List<(string CertName, string PropertyKey, bool BooleanValue)> GetAllCertProperties(XElement root, XNamespace ns) { var result = new List<(string, string, bool)>(); // 遍历所有TrustedCertificate节点 foreach (var certNode in root.Elements(ns + "TrustedCertificate")) { string certName = certNode.Element(ns + "Name")?.Value; var propertiesNode = certNode.Element(ns + "Properties"); if (propertiesNode == null) continue; foreach (var prop in propertiesNode.Elements(ns + "Property")) { string key = prop.Attribute("key")?.Value; bool value = bool.TryParse(prop.Element(ns + "BooleanValue")?.Value, out bool v) ? v : false; if (!string.IsNullOrEmpty(key)) { result.Add((certName, key, value)); } } } return result; }
调用示例
// 加载XML,替换为你自己的XML内容 string xmlContent = "你的完整XML字符串"; XDocument doc = XDocument.Parse(xmlContent); XNamespace ns = "http:not shown for security reasons"; // 替换为实际的l7命名空间地址 // 方法1:打印单份证书的所有属性 var firstCert = doc.Root.Element(ns + "TrustedCertificate"); GetPropertiesWithAttributes(firstCert, ns); // 方法2:获取所有证书的所有属性列表 var allProperties = GetAllCertProperties(doc.Root, ns); foreach (var item in allProperties) { Console.WriteLine($"证书名:{item.CertName},属性:{item.PropertyKey},值:{item.BooleanValue}"); }
内容的提问来源于stack exchange,提问作者Home of Creation
相关产品推荐
相关产品推荐

