简体   繁体   中英

Select specific node from XML document when there is two or more nodes with same name C#

Is there a way to select specific node of XML file when you have nodes with same name more then once?

For example I want to select the value of the node with name IBAN. But I have it twice as a child of some other two nodes.

I am getting node with name IBAN, put it gets first one of course.

public string GetIBANValueFromXML(XmlDocument xmlDoc)
{
    string ibanValue = "";
    XmlNodeList xnList = xmlDoc.SelectNodes("/Element[@*]");

    if (xnList != null)
    {
        foreach (XmlNode xn in xnList)
        {
            XmlNode ibanNode = xn.SelectSingleNode("IBAN");
            if (ibanNode != null)
            {
                ibanValue = ibanNode.InnerText;
            }
        }
    }
    return ibanValue;
}

If there is a clean way to accomplish this? To use this functionality but to return second IBAN node value?

You can use the XPath /Element/IBAN[2] to select the second IBAN child element of the root element named Element :

XmlNode ibanNode = xmlDoc.SelectSingleNode("/Element/IBAN[2]");
if (ibanNode != null) { ... }

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