tags:

views:

70

answers:

4

i have the following xml:

<messageContent xmlns="http://tempuri.org/" >
<Message type="MappedMessage" >
<Properties RequestId="Point-CurveRequest-8326ad44-a1cd-4a96-b4ef-1c4ad213d940"  Action="getParCurves"  EESId="EESID:NY:20100128:BASE"  Currency="USD"  Index="INX" />
<Body></Body>
</Message>
</messageContent>

and then i have this query:

var messageType = xmlDoc.SelectSingleNode("/messageContent/Message[@type]");

but no matter what i've tried, i was never able to get the node that i'm looking for. Basically i'm just try to see if there is a node (named "Message") which has a "type" property inside of it.

Has anyone have any idea here?

+1  A: 

You seem to need to establish a namespace context on your xpath, or get rid of that xmlns="http://tempuri.org/".

bmargulies
Does that hold up even if its the default namespace for the entire document?
prodigitalson
yes, thought to be perfectly sure I'd need to know what XPath package you are using -- or even what language you are in.
bmargulies
@bmargulies: Interesting, thats not the case when using SimpleXml under PHP - and while im not sure i dont think it matters when using DOMDcoument either... so long as its the default ns for the entire document.
prodigitalson
i'm using .NET. any idea?
Or A
this should explain more: http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.selectsinglenode.aspx
prodigitalson
well, if msdn solution would have worked, i wouldn't post it here...
Or A
@Or A: Can you post your implementation that uses the MSDN usage example?
prodigitalson
A: 

If messageContent is the root node you should omit it like: /Message[@type] or if you want to check the entire hierarchy of the document: //Message[@type]

prodigitalson
i tried it both, none worked!
Or A
A: 

NOt a straight forward but will work

XMLElement messageElement = (XMLElement) xmlDoc.SelectSingleNode("/messageContent/Message");
if(messageElement.HasAttribute("type"))

But the thing is if you have a node Message butdoes not contain type attribute then its not proper format of an xml.Rather i would suggest to check the content of the type attribute like below

XMLNode messageElement = xmlDoc.SelectSingleNode("/messageContent/Message[@type='MappedMessage']");
if(messageElement != null)
{
//Do SOmething
}
Ravisha
+3  A: 

There's absolutely nothing wrong with your XML - there's something wrong with your XPath expression, though :-)

Add a XML namespace manager to your code:

XmlNamespaceManager mgr = new XmlNamespaceManager(xdoc.NameTable);
mgr.AddNamespace("ns", "http://tempuri.org/");

and then use that namespace manager when you do your SelectSingleNode:

var messageType = xdoc.SelectSingleNode("/ns:messageContent/ns:Message[@type]", mgr);

That should work.

marc_s