Reputation: 353
I have these XML file:
<cteProc xmlns="http://www.portalfiscal.inf.br/cte" versao="1.04" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<CTe xmlns="http://www.portalfiscal.inf.br/cte">
<infCte versao="1.04" Id="CTexxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
<ide>
<compl>
<emit>
<rem>
<CNPJ>11111111111</CNPJ>
<IE>2222222</IE>
<xNome>Teste</xNome>
<enderReme>
<xLgr>xxxxxxx xxxxxx</xLgr>
<nro>S/N</nro>
<xCpl>AREA C</xCpl>
<xBairro>PARQ. xxxxxx</xBairro>
<cMun>125455</cMun>
<xMun>xxxxxx</xMun>
<CEP>548848</CEP>
<UF>AA</UF>
<xPais>BRASIL</xPais>
</enderReme>
<infNFe>
**<chave>1</chave>**
**<chave>2</chave>**
**<chave>3</chave>**
</infNFe>
</rem>
<exped>
<CNPJ>2342342342342</CNPJ>
<IE>15342683242345480</IE>
...........................
And I need to get values and put inside a string
I try to do this:
var ListaChave = new List<string>();
var lista = (from c in xDoc.Descendants(ns + "/rem/chave") select c.Value).ToList();
foreach (string s in lista)
{
add the values.....
}
But the s var is null. I don´t know how to get these values. Anybody can help me please!?
Upvotes: 0
Views: 139
Reputation: 31196
Use linq to xml
XDocument doc = XDocument.Load("XMLFile1.xml");
XNamespace ns = @"http://www.portalfiscal.inf.br/cte";
List<string> strList = doc.Descendants(ns+"rem").Descendants(ns+"chave").Select(e => e.Value).ToList();
and alternatively, you can have more control by doing things like
Upvotes: 3
Reputation: 28530
You're missing an element in the path you passed to Descendants
. In your XML document the chave elements are children of infNFe. Your LINQ query is looking for chave elements under "rem", and not finding any, hence the null result.
Change your query to this:
var lista = (from c in xDoc.Descendants(ns + "/rem/infNFe/chave")
select c.Value).ToList();
And you should get what you're looking for, as long as the ns is set correctly.
Upvotes: 1
Reputation: 7351
You can try with this code by just adding the infNFe:
var ListaChave = new List<string>();
var lista = (from c in xDoc.Descendants(ns + "/rem/infNFe/chave")
select c.Value).ToList();
foreach (string s in lista)
{
add the values.....
}
Upvotes: 0