Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read First Node from XMLDocument

I receive message in XML string; that I load into XmlDocument; but second node is different every time; I have given example below are three examples:

 <Message> 
    <Event1 Operation="Amended" Id="88888">Other XML Text</Event1>
 </Message>
 <Message>
    <Event2 _Operation_="Cancelled" Id="9999999"> Other XML Text </Event2>
 </Message> 
 <Message> 
    <Event3 Operation="Cancelled" Id="22222"> Other XML Text </Event3>
 </Message>

Now, I want to find out whether second node is Event1 or Event2 or Event3 and also what is value of Operation e.g. "Amended", "Cancelled", "Ordered" ?

like image 648
Ocean Avatar asked Feb 08 '11 16:02

Ocean


3 Answers

You can try

        XmlDocument xml = new XmlDocument();
        xml.LoadXml("<Message><Event1 Operation=\"Amended\" Id=\"88888\"> Other XML Text</Event1></Message>");
        Debug.WriteLine(xml.DocumentElement.ChildNodes[0].Name);
        Debug.WriteLine(xml.DocumentElement.ChildNodes[0].Attributes["Operation"].Value);
like image 102
Aliostad Avatar answered Sep 22 '22 09:09

Aliostad


XmlDocument oDoc = XmlDocument.Load(yourXmlHere);
// Your message node.
XmlNode oMainNode = oDoc.SelectSingleNode("/Message");
// Message's first subnode (Event1, Event2, ...)
XmlNode oEventNode = oMainNode.ChildNodes[0];
// Event1, Event2, ...
string sEventNodeName = oEventNode.Name;
// Value of operation attribute.
string sOpValue = oEventNode.Attributes["Operation"].Value;
like image 38
Krumelur Avatar answered Sep 21 '22 09:09

Krumelur


Off the top of my head, you could check the DocumentElement.FirstChild.Name on the XmlDocument object to retrieve the name of the first child element of the Message element.

The Operation attribute can be read using DocumentElement.FirstChild.GetAttribute("Operation").

like image 34
Matt Hogan-Jones Avatar answered Sep 21 '22 09:09

Matt Hogan-Jones