Usuário com melhor resposta
Contando elementos (nós) XML com LINQ

Pergunta
-
Boa tarde,
tenho um xml do tipo
<?XML VERSION="1.0"?> <BASEELEMENT LASTUID="ASFDAS23"> <ELEMENT UID="??2323"> <CAMPO1></CAMPO1> <READ>0</READ> </ELEMENT> <ELEMENT UID="23D23"> <CAMPO1></CAMPO1> <READ>1</READ> </ELEMENT> <ELEMENT UID="23223"> <CAMPO1></CAMPO1> <READ>0</READ> </ELEMENT> </BASEELEMENT>
Queria contar quantos elementos <read> estão com o valor 1.
Esse arquivo xml tem uns 800kb, e terá até 3 conexões simultaneas..
pensei por isso fazer em LINQ
public int QtdEmailsNaoLido() { string dPath = @"C:\\Program Files (x86)\\Mail Enable\\Postoffices\\_index.xml"; XDocument xmlDoc = XDocument.Load(dPath); XNamespace xn = "ELEMENT"; var valorElemento = xmlDoc.Root.Elements().Where(n => n.Name == (xn + "READ")).First().Value; }
tentei tb.
StreamReader str = new StreamReader(dPath); string xml = str.ReadToEnd(); var dados = (from c in XDocument.Parse(xml).Descendants("ELEMENT") let _valor = c.Element("READ").Value select new { Id = _valor }); foreach (var campos in dados.ToArray()) { Response.Write(campos.Id + "<BR>"); }
Alguém pode me ajudar?
- Editado ASPX_BR segunda-feira, 3 de fevereiro de 2014 19:12
Respostas
-
Leonardo, outra forma seria usando XPath, veja como fica simples:
XPathDocument xpath = new XPathDocument(@"c:\teste.xml"); var total = xpath.CreateNavigator().Select("/BASEELEMENT/ELEMENT/READ[text()='1']").Count;
- Marcado como Resposta ASPX_BR quarta-feira, 5 de fevereiro de 2014 14:05
Todas as Respostas
-
Só para ajudar..esse é o código original antes do refactoring
int vcount = 0; XmlDocument doc = new XmlDocument(); doc.Load(dPath); XmlNodeList No = doc.GetElementsByTagName("READ"); for (int i = 0; i < No.Count; i++) { if (No.Item(i).InnerText=="1") { vcount++; } } Response.Write(vcount.ToString());
-
Leonardo, outra forma seria usando XPath, veja como fica simples:
XPathDocument xpath = new XPathDocument(@"c:\teste.xml"); var total = xpath.CreateNavigator().Select("/BASEELEMENT/ELEMENT/READ[text()='1']").Count;
- Marcado como Resposta ASPX_BR quarta-feira, 5 de fevereiro de 2014 14:05