Parse an XML file with namespace using XPath

JORGE MALDONADO BARRERA 211 Reputation points
2023-12-14T18:48:12.5266667+00:00

I have been trying to parse an XML file with C# without success. I need to use the SelectSingleNode and SelectNodes methods to get, for example, the information for the path /cfdi:Comprobante/cfdi:Conceptos/cfdi:Concepto/cfdi:Impuestos/cfdi:Traslados. The situation I am facing is the namespace, I have not found a way to deal with it.

I have done several thing like the code below, "playing" with the nsmgr namespace variable and the path for the nodes variable without success.

XmlDocument doc = new XmlDocument();
doc.Load("c:/725.xml");
XmlElement root = GetRoot();

var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("ex", "cfdi");

var nodes = root.SelectNodes("/Comprobante/Conceptos/Concepto/Impuestos/traslados", nsmgr);

return View();

I attach the XML file for your reference.

725.xml

Bestr regards.

Developer technologies C#
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2023-12-14T19:08:53.7366667+00:00

    Try this:

    XmlDocument doc = new XmlDocument( );
    doc.Load( @"C:\725.xml" );
    
    var nsmgr = new XmlNamespaceManager( doc.NameTable );
    nsmgr.AddNamespace( "cfdi", "http://www.sat.gob.mx/cfd/4" );
    
    var nodes = doc.SelectNodes( "/cfdi:Comprobante/cfdi:Conceptos/cfdi:Concepto/cfdi:Impuestos/cfdi:Traslados", nsmgr );
    
    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-12-14T21:38:37.6933333+00:00

    xml namespaces have two parts, the namespace and the prefix. the namespace must be consistent between documents, but the prefix need not match. that is each document can define its one unique prefix for the same namespace. in your case cfdi: is a prefix for a unique namespace. in the source xml document, you need to get the actual namespace. while it is less confusing to use the same prefix's as document, but not required.

    so when you add the namespace, the prefix need only match what you use in the xpaths, but the namespace must match the value in the document.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.