Linq to XML - Null Reference exception when using linq query.n

I have a simple XML file:

<?xml version="1.0" encoding="utf-8"?>
<ConvenioValidacao>
    <convenio ven_codigo="1" tipoValidacao="CPF"></convenio>
    <convenio ven_codigo="1" tipoValidacao="MATRICULA"></convenio>
    <convenio ven_codigo="3" tipoValidacao="CPF"></convenio>
    <convenio ven_codigo="4" tipoValidacao="CPF"></convenio>
</ConvenioValidacao>

I am trying to make a simple request to this XML file using Linq to XML , here is what I do:

var myXmlDoc = XElement.Load(filePath);
var result =  from convenio in myXmlDoc.Element("ConvenioValidacao").Elements("convenio")
                 where (string)convenio.Attribute("ven_codigo") == "1" &&
                 (string)convenio.Attribute("tipoValidacao") == "CPF"
                 select convenio;

It does not work, I get an exception for the link.

What am I doing wrong?

+3
source share
3 answers

Use this instead:

var result = from convenio in myXmlDoc.Elements("convenio")
                 where (string)convenio.Attribute("ven_codigo") == "1" &&
                 (string)convenio.Attribute("tipoValidacao") == "CPF"
                 select convenio;

Since it myXmlDochas a type XElement, there is no document element, and therefore the root of this element is the root of node ( <ConveioValidacao>). Since this is the root of the node, you do not need to specify it in the method Elements, since this is the current position in the document.

myXmlDoc myXmlElement, .

+9

. , ConveioValidacao , , XEelemnt.Load(), ConveioValidacao , u Andrew.

+1

Try descendants instead of elements

var result =  from convenio in myXmlDoc.Descendants("ConveioValidacao").Descendants("convenio")
                 where (string)convenio.Attribute("ven_codigo") == "1" &&
                 (string)convenio.Attribute("tipoValidacao") == "CPF"
                 select convenio;
0
source

Source: https://habr.com/ru/post/1716002/


All Articles