简体   繁体   中英

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'm trying to do a simple query against this xml file using Linq to XML , here is what i'm doing:

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 is not working, I'm getting null reference exception.

What I'm doing wrong?

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 myXmlDoc is of type XElement there is no "document element" and as such the root of the element is the root node ( <ConveioValidacao> ). Since this is the root node you don't need to specify it in an Elements method since that is current position in document.

As a side note, I recommend that you rename myXmlDoc to myXmlElement to reduce confusion.

.Element方法获取给定元素的第一个子元素,在这里ConveioValidacao不是子元素,它是父元素,当你通过XEelemnt.Load()方法加载时,它获取ConveioValidacao及其子元素,所以你应该使用Andrew的码。

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM