Search code examples
c#xml

Find specific child node by name from XmlNode


I have an XML document, I'm looping through particular elements by name, and finding a value inside that node. If it matches what I'm looking for, I then need to get the values of some child nodes... but the "GetElementsByTagName" doesn't exist on XmlNode. Is there another way to find elements by tag name from XmlNode?

I have no control over the XML, and the structure is not consistent I cannot rely on index for most of the data I need.

XmlNodeList offers = xml.GetElementsByTagName("Offer");   
foreach (XmlNode offer in offers){  
    var offerId = offer.FirstChild.FirstChild.InnerText //Only consistently placed element
    if (offerId == queryId){  
        //Need to get some values from large complex XML inside `offer`
    }  
}

Tried several properties of XmlNode and couldn't find a way to accomplish this.

EDIT

The XML structure that could be literally anything because it's not actually relevant to the question, hence it getting almost immediately and accurately answered:

<Offer>
  <Completely>
    <Irrelevant>
      TEXT
    </Irrelevant>
  </Completely>
  <ButYouAskedForIt>
    <AfterItWasAnswered>
      Now give me the point back
    </AfterItWasAnswered>
  </ButYouAskedForIt>
</Offer>
<Offer>
  <Completely>
    <Irrelevant>
      TEXT
    </Irrelevant>
  </Completely>
  <ButYouAskedForIt>
    <AfterItWasAnswered>
      Now give me the point back
    </AfterItWasAnswered>
  </ButYouAskedForIt>
</Offer>
    

Solution

  • GetElementsByTagName returns an IEnumerable. Cast its results to XmlElement, and then you can use all the available methods of that class.

    var offers = xml.GetElementsByTagName("Offer").OfType<XmlElement>().ToList();
    foreach (XmlElement offer in offers)
    {
        var offerId = offer.FirstChild.FirstChild.InnerText //Only consistently placed element
        if (offerId == queryId)
        {
            //Need to get some values from large complex XML inside `offer`
        }
    }