如何从Soap Request中读取SecurityToken和Signature值

时间:2014-06-26 14:02:39

标签: c# xml linq soap

我已捕获肥皂请求

<s:Envelope xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:s="http://www.w3.org/2003/05/soap-envelope">
  <s:Header>
    <a:Action s:mustUnderstand="1">http://tempuri.org/IService/GetAccountsData</a:Action>
    <h:SecurityToken xmlns:h="http://tempuri.org/">SEC00001</h:SecurityToken>
    <a:MessageID>urn:uuid:d54052d7-fed7-40f4-9b3f-f857d0804ffb</a:MessageID>
    <a:ReplyTo>
      <a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
    </a:ReplyTo>
  </s:Header>
  <s:Body>
    <CustomerCredential xmlns="http://tempuri.org/">
      <CustomerID>C001</CustomerID>
      <RuleId>2.1</RuleId>
      <Signature i:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" />
    </CustomerCredential>
  </s:Body>
</s:Envelope>

我需要读取c#中的SecurityToken和Signature值。

我正在尝试使用以下代码,但无法读取SecurityToken和Signature值。

XNamespace ns = doc.Root.Name.Namespace;

var elements = from c in doc.Descendants(ns + "Header")
               select c;

请发表您的评论。

1 个答案:

答案 0 :(得分:1)

我建议使用XPath表达式的以下解决方案。请考虑以下代码:

    string filename = "SOAP.xml";
    XmlDocument document = new XmlDocument();
    document.Load(filename);
    XPathNavigator navigator = document.CreateNavigator();
    // use XmlNamespaceManager to resolve ns prefixes
    XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable);
    manager.AddNamespace("h", "http://tempuri.org/");
    // use XPath expression to select XML nodes
    XPathNodeIterator nodes = navigator.Select("//h:SecurityToken",manager);
    if ( nodes.MoveNext() )
        Console.WriteLine(nodes.Current.ToString());
    else
        Console.WriteLine("Empty Element");
    // and now for the Signature Element, without ns prefix
    nodes = navigator.Select("//Signature", manager);
    if (nodes.MoveNext())
        Console.WriteLine(nodes.Current.ToString());
    else
        Console.WriteLine("Empty Element");

有关详细信息,请参阅类XPathNavigator http://msdn.microsoft.com/en-us/library/6k4x060d.aspx

的MSDN文档