Extract child tags from an XML

Asked

Viewed 355 times

0

I am consuming a served recipe and it returns me an XML as for example:

<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 docZip tags from XML using Xelement with Linq and every time returned empty.

Some codes I 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")
                          };
  • Raul, put the code of what you’ve tried to do to help us better

  • I put some that I remembered I used.

2 answers

1


What is wrong basically in your code is the following:

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

Can solve like 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 concatenei the namespace (variable df) to search the Node "loteDistDFeInt" and extract the elements (.Elements()).
Then I read each value of the attributes "NSU" and "schema".

Here a fiddle demonstrating the operation: https://dotnetfiddle.net/aruXTh

0

I managed to solve.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.