tags:

views:

433

answers:

3

Hi all,

I have the below fragement of XML, notice that the Reference node holds a URI which links to the Id attribute of the Body node.

 <Reference URI="#Body">
  <SOAP-ENV:Body Id="Body" xmlns:SOAP-ENV="http://www.dingo.org"&gt;
    <ns0:Add xmlns:ns0="http://www.moo.com"&gt;
      <ns0:a>2</ns0:a>
      <ns0:b>3</ns0:b>
    </ns0:Add>
  </SOAP-ENV:Body>

If I had the value of the URI attribute how would I then get the whole Body XMLNode? I presume this would be best done via an XPath epression but haven't any clue on XPath. Note that the XML will not always be so simple. I'm doing this in c# btw :)

Any ideas?

Thanks

Jon

EDIT: I wouldn't know the XML structure or namespaces before hand, all I would know is that the reference element has the ID of the xmlNode i want to retrieve, hope this is sligtly clearer.

+2  A: 

You can add a condition that applies to a relative (or absolute node) to any step of an XPath expression.

In this case:

//*[@id=substring-after(/Reference/@URI, '#')]

The //* matches all elements in the document. The part in [] is a condition. Inside the condition the part of the URI element of the root References node is taken, but ignoring the '#' (and anything before it).

Sample code, assuming you have loaded your XML into XPathDocument doc:

var nav = doc.CreateNavigator();
var found = nav.SelectSingleNode("//*[@id=substring-after(/Reference/@URI, '#')]");
Richard
sorry, I'm not really sure what you mean, I also wouldn't know the XML structure before hand, basically I recieve this XML and need to get the node referenced by the URI attribute in the Reference tag
Jon
Will update... in a few moments.
Richard
+1  A: 

If you have the value of the URI attribute in a variable you could use

myXmlDocument.DocumentElement.SelectSingleNode("//SOAP-ENV:Body[ID='pURI']")

where pURI is the value of the URI attribute and myXmlDocument is the Xml Document object

Nikos Steiakakis
You need to add a namespace mapping.
Richard
A: 

Something like this:

XmlDocument requestDocument = new XmlDocument();
requestDocument.LoadXml(yourXmlString);
String someXml = requestDocument.SelectSingleNode(@"/*[local-name()='Reference ']/*[local-name()='Body']").InnerXml;
Philippe
"SOAP-ENV" is the namespace tag, not the local name.
Richard
I wouldn't know the xml strucutre or namespaces before hand though, see my edit
Jon
Richard: my bad
Philippe