0

This is my source XML :

<?xml version="1.0" encoding="UTF-8"?>
<cteProc xmlns="http://www.portalfiscal.inf.br/cte" versao="1.04">
<CTe>
<infCte versao="1.04" Id="CTe35121004211559000111570010000118991000119858">
<ide>
     <cUF>35</cUF>
     <cCT>00011985</cCT>
     <CFOP>7358</CFOP>
     <natOp>PRESTACAO DE SERVICO DE TRANSPORTE</natOp>
     <forPag>1</forPag>
     <mod>57</mod>
     <serie>1</serie>
     <nCT>11899</nCT>
     <dhEmi>2012-10-01T09:34:45</dhEmi>
</ide>
<compl>
<emit>
<rem>
<dest>
<vPrest>
<imp>
<infCTeNorm>
</infCte>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
</CTe>
<protCTe versao="1.04">
</cteProc>

I have read this file with this code :

      XmlTextReader reader = new XmlTextReader(@"C:\Separados\56000858_v01.04-procCTe.xml");
        XmlNodeType type;
        while (reader.Read())
        {
            type = reader.NodeType;
            if (type == XmlNodeType.Element)
            {
                if (reader.Name == "cUF")
                {  reader.Read(); Xmunini = reader.Value; textBox1.Text = Xmunini;}

                if (reader.Name == "cCT")
                {  reader.Read(); vtprest = reader.Value; textBox2.Text = vtprest;}

                if (reader.Name == "natOp")
                {   reader.Read(); UFIni = reader.Value; textBox3.Text = UFIni; }

                if (reader.Name == "nCT")
                { reader.Read(); NCT = reader.Value; textBox4.Text = NCT;}

But, i have read in many post here , the method with LINQ is more efficient, i have try write this :

    var custs45 = from c in XElement.Load(@"C:\Separados\56000858_v01.04-procCTe.xml").Elements("Cte")

    select new { 
    CFOP = c.Element("CFOP").Value,
    xMunIni = c.Element("xMunIni").Value 
    };

My question is how to assign CFOP and Xmunini to a variable?? i have write this but do not show anything

    string CFF;
    foreach (var valores in custs45)
    { 
      CFF = valores.CFOP.ToString() ;        
    }
4

1 回答 1

1

您找不到节点,因为根节点已删除命名空间。这是解决方案:

XDocument xdoc = XDocument.Load(path_to_xml);
XNamespace ns = "http://www.portalfiscal.inf.br/cte";
string CFF = (string)xdoc.Descendants(ns + "CFOP").Single();

此外,您在CTe元素名称中有拼写错误。而您缺少CFOP的不是CTe. 而且您的 xml 中仍然没有xMunIni元素。

您的原始查询应如下所示:

XNamespace ns = "http://www.portalfiscal.inf.br/cte";
var custs45 = from ide in XElement.Load(path_to_xml).Descendants(ns + "ide")
              select new
              {
                  CFOP = (string)ide.Element(ns + "CFOP"),
                  xMunIni = (string)ide.Element(ns + "xMunIni")
              };
于 2012-12-05T18:25:56.967 回答