Following is the XML from which I am trying to extract a child element.
<?xml version="1.0" encoding="UTF8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header xmlns="http://SomeValue/SomeValue/2009/01/SomeValue.xsd">
<Session>
<SessionId>SomeValue</SessionId>
<SequenceNumber>1</SequenceNumber>
<SecurityToken>SomeValue</SecurityToken>
</Session>
</soap:Header>
<soap:Body>
<Security_AuthenticateReply xmlns="http://SomeValue/SomeValue">
<processStatus>
<statusCode>P</statusCode>
</processStatus>
</Security_AuthenticateReply>
</soap:Body>
</soap:Envelope>
public static string AssignSecurityToken(string response)
{
string Token = "";
XNamespace ns = "http://schemas.xmlsoap.org/soap/envelope/";
XElement xdoc = XElement.Parse(response);
XElement root = xdoc.Descendants(ns + "Header").First();
Token = root.Element("Session").Element("SecurityToken").Value;
Token = root.Descendants("Session").Descendants().Where(n => n.Name == "SecurityToken").FirstOrDefault().Value;
return Token;
}
I want to extract the element Security Token.
Following are the things that I have already worked on:
Tried extracting the element using the approach suggested in the post How to get value of child node from XDocument
Also posting some code for reference. Both the statements that are assigning values to the Token variable are throwing "Object not set to an instance of an object"exception.
Thanks in advance.
You need to take into account the Header
's namepace.
public static string AssignSecurityToken(string response)
{
XNamespace ns1 = "http://schemas.xmlsoap.org/soap/envelope/";
XNamespace ns2 = "http://SomeValue/SomeValue/2009/01/SomeValue.xsd";
var envelope = XElement.Parse(response);
var header = envelope.Element(ns1 + "Header");
var session = header.Element(ns2 + "Session");
var security_token = session.Element(ns2 + "SecurityToken");
return security_token.Value;
}
Actually you could go ahead and just call
return XElement.Parse(response).Descendants()
.First(x => x.Name.LocalName == "SecurityToken").Value;