Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ember.js/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 读取XML LINQ时出错_C#_Xml_Linq_Linq To Xml - Fatal编程技术网

C# 读取XML LINQ时出错

C# 读取XML LINQ时出错,c#,xml,linq,linq-to-xml,C#,Xml,Linq,Linq To Xml,这是我的源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>

这是我的源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>
但是,我在这里的许多帖子中读到,使用LINQ的方法更有效,我试着写下以下内容:

    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 
    };
我的问题是如何将CFOP和Xmunini分配给变量??我写了这个,但没有显示任何内容

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

找不到节点,因为根节点具有命名空间。以下是解决方案:

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")
              };

xml中的
+,-,--
是什么?根节点的结束标记在哪里?其他结束标记在哪里?请正确格式化您的XML示例。有没有可能,该XML是从Internet Explorer复制的?我已编辑了XML源文件,很抱歉,我已从IET复制该XML仍然无效。您的打开和关闭标记不匹配。
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")
              };