简体   繁体   English

从XMLDocument中读取第一个节点

[英]Read First Node from XMLDocument

I receive message in XML string; 我收到XML字符串中的消息; that I load into XmlDocument ; 我加载到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 eg "Amended", "Cancelled", "Ordered" ? 现在,我想知道第二个节点是Event1还是Event2Event3 ,还有什么是Operation的值,例如“Amended”,“Cancelled”,“Ordered”?

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);

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. 在我的脑海中,您可以检查XmlDocument对象上的DocumentElement.FirstChild.Name以检索Message元素的第一个子元素的名称。

The Operation attribute can be read using DocumentElement.FirstChild.GetAttribute("Operation"). 可以使用DocumentElement.FirstChild.GetAttribute("Operation").读取Operation属性DocumentElement.FirstChild.GetAttribute("Operation").

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM