lemunk
lemunk

Reputation: 2636

XML Soap Get Element From Xelement

the xml that i get via a response stream:

<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soapenv:Body>
        <generateSSOResponse xmlns="http://url.com">
            <generateSSOReturn>2DKtjZNq58THggh42lNsGvgGTjF8RSBA</generateSSOReturn>
        </generateSSOResponse>
    </soapenv:Body>
</soapenv:Envelope>

The code is use to try and get the "generateSSOResponse" token value.

var xmlDoc = XElement.Parse(s);

var ssoToken = xmlDoc.XPathSelectElement("/soapenv:Envelope[@xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"]/soapenv:Body/generateSSOResponse[@xmlns=\"http://ws.configureone.com\"]/generateSSOReturn");

Error: Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function.

Saying i need a namespace manager? i though that's when dealing with XMLdoc not xElement? Whats the solution here?

EDIT: variable "s" is the response stream code as :

using (var mem = new MemoryStream())
{
    rstream.CopyTo(mem);

    var b = mem.ToArray();
    var s = System.Text.Encoding.UTF8.GetString(b);

Upvotes: 2

Views: 1146

Answers (2)

lemunk
lemunk

Reputation: 2636

Ok so Charles Mager gave an answer using XMLtoLINQ as I was trying to use Xelement. However it turns out the ERP the code is being embedded into doesn't support linq (bummer).

So here's the solution i got working without XMLtoLINQ:

XmlDocument mydoc = new XmlDocument();
    XmlNamespaceManager manager = new XmlNamespaceManager(mydoc.NameTable);
    manager.AddNamespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/"); 
    manager.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
    manager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
    manager.AddNamespace("rsp","http://url.com");


    mydoc.LoadXml(s);
    var mytoken = mydoc.SelectSingleNode("//rsp:generateSSOReturn", manager);

Hope this helps anyone else who is in the same predicament as I was.

Upvotes: 0

Charles Mager
Charles Mager

Reputation: 26213

Honestly, it'd be far simpler to use LINQ to XML as it was intended:

XNamespace ns = "http://url.com";

var token = (string)doc.Descendants(ns + "generateSSOReturn").Single();

See this fiddle for a working example. If you did want to use XPath then yes, you would need a namespace manager to allow the XPath navigator to resolve all the prefixes in your expression.

As an aside, you could also parse your XML direct from the stream:

var doc = XDocument.Load(rstream);

Upvotes: 1

Related Questions