7

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" ?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ocean
  • 655
  • 2
  • 8
  • 21

3 Answers3

9

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);
Aliostad
  • 80,612
  • 21
  • 160
  • 208
2
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;
Krumelur
  • 32,180
  • 27
  • 124
  • 263
2

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").

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Matt Hogan-Jones
  • 2,981
  • 1
  • 29
  • 35