C#如何从SAML响应XML中提取InResponseTo属性值
失败原因
你的两次尝试均未正确处理XML命名空间:XML中的saml:、samlp:只是命名空间别名,实际对应唯一的命名空间URI,查询带前缀的节点时必须绑定对应URI才能命中目标。
可行实现方案
方案1:使用XDocument
using System.Xml.Linq; // 加载XML文件 XDocument xdoc = XDocument.Load("samlresponse.xml"); // 绑定saml前缀对应的命名空间URI,和XML中定义的完全一致 XNamespace samlNs = "urn:oasis:names:tc:SAML:2.0:assertion"; // 如需查询samlp前缀的节点,可额外声明samlp的命名空间 XNamespace samlpNs = "urn:oasis:names:tc:SAML:2.0:protocol"; // 提取<saml:SubjectConfirmationData>节点的InResponseTo属性值 List<string> inResponseToList = xdoc.Descendants(samlNs + "SubjectConfirmationData") .Select(node => node.Attribute("InResponseTo")?.Value) .Where(val => !string.IsNullOrEmpty(val)) .ToList(); // 如需提取根节点<samlp:Response>的InResponseTo属性,使用以下代码 string rootInResponseTo = xdoc.Root?.Attribute("InResponseTo")?.Value;
方案2:使用XmlDocument
using System.Xml; XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load("samlresponse.xml"); // 初始化命名空间管理器,绑定前缀和对应命名空间URI XmlNamespaceManager nsManager = new XmlNamespaceManager(xmlDocument.NameTable); nsManager.AddNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol"); nsManager.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion"); // 提取<saml:SubjectConfirmationData>节点的InResponseTo属性值 XmlNodeList dataNodes = xmlDocument.SelectNodes("//saml:SubjectConfirmationData", nsManager); foreach (XmlNode node in dataNodes) { string inResponseTo = node.Attributes?["InResponseTo"]?.Value; // 自行处理拿到的属性值 } // 如需提取根节点<samlp:Response>的InResponseTo属性,使用以下代码 XmlNode rootNode = xmlDocument.SelectSingleNode("/samlp:Response", nsManager); string rootInResponseTo = rootNode?.Attributes?["InResponseTo"]?.Value;
注:你的XML中存在两处InResponseTo属性,分别在根节点<samlp:Response>和<saml:SubjectConfirmationData>节点上,可根据实际需求选择提取对应位置的值。
内容的提问来源于stack exchange,提问作者Rocky3151
相关产品推荐
相关产品推荐

