-1

I have this XML file, I can read all the the nodes

<?xml version="1.0" encoding="UTF-8"?>
<cteProc xmlns="http://www.portalfiscal.inf.br/cte" versao="1.04">
    <CTe xmlns="http://www.portalfiscal.inf.br/cte">
        <infCte versao="1.04" ID="CTe3512110414557000014604"></infCte>
    </CTe>
</cteProc> 

I have tried reading this using C#

string chavecte;        
string CaminhoDoArquivo = @"C:\Separados\13512004-procCTe.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(CaminhoDoArquivo); //Carregando o arquivo
chavecte = xmlDoc.SelectSingleNode("infCTe")
                    .Attributes.GetNamedItem("Id").ToString();

but something is wrong with this code.

Kjartan
  • 18,591
  • 15
  • 71
  • 96
alejandro carnero
  • 1,774
  • 7
  • 27
  • 43

3 Answers3

4

If you want to use Linq To Xml

var xDoc = XDocument.Load(CaminhoDoArquivo);
XNamespace ns = "http://www.portalfiscal.inf.br/cte";
var chavecte = xDoc.Descendants(ns+"infCte").First().Attribute("id").Value;

PS: I am assuming your xml's invalid line is as

<infCte versao="1.04" id="CTe3512110414557000014604"></infCte>
I4V
  • 34,891
  • 6
  • 67
  • 79
2

replace

chavecte = xmlDoc.SelectSingleNode("infCTe").Attributes.GetNamedItem("Id").Value;

with

XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("ab", "http://www.portalfiscal.inf.br/cte");

chavecte = xmlDoc.SelectSingleNode("//ab:infCte", nsmgr)
                 .Attributes.GetNamedItem("Id").Value;

I've also noticed that infCte doesn't have the ID attribute properly defined in your xml

0

Another possible solution is:

string CaminhoDoArquivo = @"C:\Separados\13512004-procCTe.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(CaminhoDoArquivo); //Carregando o arquivo

// Select the node you're interested in
XmlNode node = xmlDoc.SelectSingleNode("/cteProc/CTe/infCte");
// Read the value of the attribute "ID" of that node
string chavecte = node.Attributes["ID"].Value;
Tanvir
  • 1,453
  • 2
  • 16
  • 32