Extract child tags from an XML

0

I'm consuming a recipe server and it returns me an XML like:

<retDistDFeInt xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" versao="1.01" xmlns="http://www.portalfiscal.inf.br/nfe">
  <tpAmb>1</tpAmb>
  <verAplic>1.1.9</verAplic>
  <cStat>138</cStat>
  <xMotivo>Documento(s) localizado(s)</xMotivo>
  <dhResp>2018-10-09T13:01:42-03:00</dhResp>
  <ultNSU>000000000000000</ultNSU>
  <maxNSU>000000000000013</maxNSU>
  <loteDistDFeInt>
    <docZip NSU="000000000000001" schema="resNFe_v1.01.xsd">XYZABCdUKAAF...etc</docZip>
    <docZip NSU="000000000000002" schema="resNFe_v1.01.xsd">XYZABCdUKAAF...ec</docZip>
  </loteDistDFeInt>
</retDistDFeInt>

I've tried several ways to extract the values of the docZip tags from XML using XElement with Linq and it all returned empty.

Some codes I've tried:

var retorno = from nota in xmlRetorno.Elements("retDistDFeInt") select nota;

var retorno = from nota in xmlRetorno.Elements("loteDistDFeInt") select nota;

var points = xmlRetorno.Descendants("loteDistDFeInt");
var point = points.FirstOrDefault();

var retorno = from nota in xmlRetorno.Elements("loteDistDFeInt")
                          select new
                          {
                              nsu = (string)nota.Element("NSU"),
                              schema = (string)nota.Element("schema")
                          };
    
asked by anonymous 10.10.2018 / 19:59

2 answers

1

What's basically wrong with your code is this:

  • is not using namespace to navigate to XElement ;
  • is treating attribute as element. "NSU" is an attribute in the "docZip" element.

You can solve this:

XNamespace df = xmlRetorno.Name.Namespace;
var loteDistDFeIntElements = xmlRetorno.Element(df + "loteDistDFeInt").Elements();
var retorno = from nota in elements.Element(df + "loteDistDFeInt").Elements()
          select new
          {
              nsu = (string)nota.Attribute("NSU").Value,
              schema = (string)nota.Attribute("schema").Value
          };

I basically concatenated the namespace (variable df ) to search the node "loteDistDFeInt" and extract the elements ( .Elements() ). Then I read each value of the "NSU" and "schema" attributes.

Here's a fiddle showing how it works: link

    
10.10.2018 / 20:59
0

I was able to resolve it.

var retorno = (from nota in xmlRetorno.Elements()
                           where nota.Name.LocalName.Equals("loteDistDFeInt")
                           select nota).FirstOrDefault().Value;
    
10.10.2018 / 21:40