Search code examples
c#xmlxml-parsingxmldocument

How to find nodes in an XML


I have loaded the following XML file using xml.Load("myfile.xml"); where xml is of type XmlDocument:

<?xml version="1.0" encoding="ISO-8859-1"?>
    <DTE xmlns="http://www.sii.cl/SiiDte" version="1.0">
        <Documento ID="E000000005T033F0114525415">
            <Encabezado>
                <IdDoc>
                    <TipoDTE>33</TipoDTE>
                    <Folio>114525415</Folio>
                    <FchEmis>2021-11-02</FchEmis>
                    <FmaPago>1</FmaPago>
                    <FchVenc>2021-11-02</FchVenc>
                </IdDoc>
            </Encabezado>
        </Documento>
    </DTE>

How can I get Folionode?

I have tried with:

  xml.DocumentElement.SelectSingleNode("/DTE/Documento/Encabezado/IdDoc/Folio");
  xml.DocumentElement.SelectNodes("DTE/Documento/Encabezado/IdDoc/Folio")
  xml.DocumentElement.SelectSingleNode("//DTE/Documento/Encabezado/IdDoc/Folio");
  xml.DocumentElement.SelectSingleNode("/Documento/Encabezado/IdDoc/Folio");
  xml.DocumentElement.SelectSingleNode("Documento/Encabezado/IdDoc/Folio");
  xml.DocumentElement.SelectSingleNode("/Encabezado/IdDoc/Folio");
  xml.DocumentElement.SelectNodes("/DTE/Documento/Encabezado/IdDoc/Folio")

when I debug xml.DocumentElement I see that the element is DTE so I think xml.DocumentElement.SelectSingleNode("Documento/Encabezado/IdDoc/Folio") should do it.

When I get xml.DocumentElement.FirstChild I get Documento node.

With xml.DocumentElement.FirstChild.FirstChild I get Encabezado node.

With xml.DocumentElement.FirstChild.FirstChild.FirstChild I get IdDoc node.

If I use xml.DocumentElement.FirstChild.FirstChild.FirstChild.SelectSingleNode("Folio"), returned value is null.

If I use xml.DocumentElement.FirstChild.FirstChild.FirstChild.ChildNodes, I get the 5 elements.

Then I could use xml.DocumentElement.FirstChild.FirstChild.FirstChild.ChildNodes[1].InnerText to get Folio value.

I can traverse the XML but, how can I do it to get the element directly?

Thanks Jaime


Solution

  • It is better to use LINQ to XML API for your task. It is available in the .Net Framework since 2007.

    The provided XML has a default namespace. It needs to be declared and used, otherwise it is imposable to find any XML element.

    c#

    void Main()
    {
        const string filename = @"e:\Temp\jstuardo.xml";
    
        XDocument xdoc = XDocument.Load(filename);
        XNamespace ns = xdoc.Root.GetDefaultNamespace();
    
        string Folio = xdoc.Descendants(ns + "Folio")
          .FirstOrDefault()?.Value;
    
        Console.WriteLine("Folio='{0}'", Folio);
    }
    

    Output

    Folio='114525415'