1

I have to select specific node from the WCF request OperationContext.Current.RequestContext.RequestMessage.ToString()

The problem is that namespaces are changeing prefixes between requests:

So once it is:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
  <s:Body>
  </s:Body>
</s:Envelope>

and other time it is:

<soapenv:Envelope xmlns:mes="MessageContracts" xmlns:req="RequestMessages" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
  </soapenv:Body>
</soapenv:Envelope>

How can I assure that I always get Body node correctly?

Kumar V
  • 8,810
  • 9
  • 39
  • 58
Johnny
  • 425
  • 3
  • 15
  • It is not the namespace (`http://schemas.xmlsoap.org/soap/envelope/`) which is changing, but the namespace prefix (from `s` to `soapenv`). – flup Jan 23 '13 at 10:43

2 Answers2

0

If you are using an XPATH to select the node, you can ignore the namespace (and it's abbreviation prefix) when selecting nodes by selecting on the basis of local-name(). There is an example of this in the following SO article:-

For your XML documents above, the following Xpath query will return a count of 1 for both documents.

count(/*[local-name() = 'Envelope']/*[local-name() = 'Body'])
Community
  • 1
  • 1
Nick Ryan
  • 2,662
  • 1
  • 17
  • 24
0

It doesn't matter what the prefixes are as long as the nodes are using the same namespace consistently (which they are in your example). You just need to make sure that you create a prefix->namespace mapping for the namespace correctly when you do your selection:

The following code should work as-is for both of your example xmls:

// assuming XmlDocument doc has already been loaded with the XML response
XmlNamespaceManager nsm = new XmlNamespaceManager(doc.NameTable);
nsm.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
XmlNode body = doc.SelectSingleNode("/soap:Envelope/soap:Body", nsm);

Working ideone example

JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • Hi. Thanks, I thought exactly the same and I did exactly so at the beginning - but it did not work, and that is the purpose of my post. Let me check again if I haven't make some simple mistake – Johnny Jan 23 '13 at 10:47
  • Hehe. The problem was really in my Xpath statement. I was selecting xmlReq.SelectSingleNode("bd:Body", ns) - which was giving the null result! But should't this select all Body nodes in the document? – Johnny Jan 23 '13 at 10:59
  • No, `bd:Body` would only select Body nodes that were immediately below the context node. `//bd:Body` would select all Body nodes in the document. – JLRishe Jan 23 '13 at 11:07