Read Node from XMLDocument First

I get a message in an XML string; what i upload to XmlDocument; but the second node is different every time; I gave an example below, these 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 if there is a second node Event1or Event2or Event3, and also what is the value of the operation, for example. "Changes", "Canceled", "Ordered"?

+5
source share
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);
+8
source

At the top of my head, you can check DocumentElement.FirstChild.Nameon the object XmlDocumentto get the name of the first child of the Message element.

Operation DocumentElement.FirstChild.GetAttribute("Operation").

+2
XmlDocument oDoc = XmlDocument.Load(yourXmlHere);
// Your message node.
XmlNode oMainNode = oDoc.SelectSingleNode("/Message");
// Message 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;
+1

All Articles