简体   繁体   中英

Select a child node in XML with specific name using C#

I am trying to find a child element with tag name Reason. I have XML doc that is basically contains bunch of elements with Entity name. Reason tag is somewhere inside of Entity(along with other elements).

void IParseResponse.ParseResponseData(XmlDocument responseDocument)
{
    List<string> reasons = new List<string>();
    var reasonValue = "";
    var entityList = responseDocument.GetElementsByTagName("Entity");

    if (entityList != null)
    {
        foreach (XmlNode reason in entityList)
        {   
            reasonValue = //look into current Entity element, find Reason in it and get it's inner text.
            reasons.Add(reasonValue);
        }
    }
}

This is location of Reason element.

<Entity>
  <WatchList>
     <Match ID="1">
        <MatchDetails>
          <Reason>

Does anybody have experience with this?

Here's how you can get all the Reason elements.

var xml = "<Entity> <WatchList><Match ID=\"1\"><MatchDetails><Reason>asdasd</Reason></MatchDetails></Match></WatchList></Entity>";

var x = XDocument.Parse(xml);
var reasons = x.Descendants("Reason").ToList();
foreach (var reason in reasons)
{
    Console.WriteLine(reason.Value);
}

If you give us a more complete example of your XML I can improve the answer.

Edit:

If you want to use XmlDocument instead you could do this:

XmlNodeList nodes = responseDocument.GetElementsByTagName("Reason");

for (int i = 0; i < nodes.Count; i++)
{
    Console.WriteLine(nodes[i].InnerText);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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