You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用LINQ或Lambda从OuterXml结果中提取chNFe值?

解决XML中提取chNFe值的问题

你的代码无法获取chNFe值的核心原因是XML存在命名空间,根元素retEnviNFe声明了xmlns="http://www.portalfiscal.inf.br/nfe",所有子元素都属于这个命名空间,直接使用元素名称查询会匹配不到。

以下是正确的实现方案:

步骤1:定义XML命名空间

首先声明对应的命名空间对象:

XNamespace ns = "http://www.portalfiscal.inf.br/nfe";

步骤2:使用LINQ查询获取chNFe值

写法一:LINQ查询表达式

var retorno = ws.nfeAutorizacaoLoteAsync(newNode).Result;
var docC = XDocument.Parse(retorno.nfeResultMsg.OuterXml);

XNamespace ns = "http://www.portalfiscal.inf.br/nfe";
var chaveRetorno = (from protNFe in docC.Descendants(ns + "protNFe")
                    from infProt in protNFe.Descendants(ns + "infProt")
                    from chNFe in infProt.Descendants(ns + "chNFe")
                    select chNFe.Value).FirstOrDefault();

写法二:Lambda表达式

var retorno = ws.nfeAutorizacaoLoteAsync(newNode).Result;
var docC = XDocument.Parse(retorno.nfeResultMsg.OuterXml);

XNamespace ns = "http://www.portalfiscal.inf.br/nfe";
var chaveRetorno = docC.Descendants(ns + "chNFe")
                       .Select(e => e.Value)
                       .FirstOrDefault();

原代码问题说明

  • 原代码直接使用docC.Elements()遍历根元素的直接子节点,而chNFe是嵌套在protNFe→infProt下的深层节点,无法直接遍历到。
  • 没有处理XML命名空间,导致元素名称匹配失败。

内容的提问来源于stack exchange,提问作者Guto Barroso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 02:35:23