3

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?

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

Comments

1

.Element method gets first child element of the given element, in here ConveioValidacao is not a child element, it is the parent element, when you load by XEelemnt.Load() method it gets ConveioValidacao and it's child elements, so u should use Andrew's code.

Comments

0

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;

1 Comment

That stops it from throwing an exception but it doesn't solve the problem. myXmlDoc is an XElement not an XDocument which means that the <ConveioValidacao> node is not a descendant of it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.