Search code examples
c#.netxmlselectnodes

Parsing XML with C# - Not able to select Nodes while GetElementsByTagName working


I'm trying to select nodes in c# within a XML file with below example.

<dsEq xmlns="http://tempuri.org/dsEq.xsd">
   <Dago>
      <EID>XX</EID> 

below code is working :

private static List<string> getListOfEID(XmlDocument xmlDoc)
{
    List<string> ListingEID = new List<string>();
    XmlNodeList nodeCollection = xmlDoc.GetElementsByTagName("EID");

    foreach (XmlNode elt in nodeCollection)
    {
        ListingEID.Add(elt.InnerText.ToString());
    }
    return ListingEID;
}

While I tried a lot of things, without success with Selectnodes method, not working :

private static List<string> getListOfEID(XmlDocument xmlDoc)
{
    List<string> ListingEID = new List<string>();
    XmlNodeList nodeCollection = xmlDoc.SelectNodes("/dsEq/Dago/EID");

    foreach (XmlNode elt in nodeCollection)
    {
        ListingEID.Add(elt.InnerText.ToString());
    }
    return ListingEID;
}

Thanks in advance !

tried a lot of different xPath without success.

adding nameSpace seems not helping

    private static List<string> getListOfEID(XmlDocument xmlDoc)
    {
        List<string> ListingEID = new List<string>();

        XmlNamespaceManager nameManager = new XmlNamespaceManager(xmlDoc.NameTable);
        nameManager.AddNamespace("myEID","/dsEq/Dago");

        XmlNodeList nodeCollection = xmlDoc.SelectNodes("myEID");

        foreach (XmlNode elt in nodeCollection)
        {
            ListingEID.Add(elt.InnerText.ToString());
        }
        return ListingEID;
    }

==> Show nil node


Solution

  • I too think it is super simple with Linq to XML as @Yitzhak Khabinsky showed already. Yours is not working because you are not using Xpath correctly.

    void Main()
    {
        var doc = new XmlDocument();
        doc.LoadXml(sample);
        var eids = getListOfEID(doc);
        foreach (var eid in eids)
        {
            Console.WriteLine(eid);
        }
    }
    
    private static List<string> getListOfEID(XmlDocument xmlDoc)
    {
        List<string> ListingEID = new List<string>();
    
        XmlNamespaceManager nameManager = new XmlNamespaceManager(xmlDoc.NameTable);
        nameManager.AddNamespace("x","http://tempuri.org/dsEq.xsd");
        XmlNodeList nodeCollection = xmlDoc.SelectNodes("//x:EID", nameManager);
    
        foreach (XmlNode elt in nodeCollection)
        {
            ListingEID.Add(elt.InnerText.ToString());
        }
        return ListingEID;
    }
    
    static readonly string sample = @"<dsEq xmlns=""http://tempuri.org/dsEq.xsd"">
       <Dago>
          <EID>XX</EID>
        </Dago>
        <Dago>
          <EID>YY</EID>
        </Dago>
        <Dago>
          <EID>ZZ</EID>
        </Dago>
    </dsEq>";