如何使用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
相关产品推荐
相关产品推荐

