views:

42

answers:

3

I have a XML source with nodes like this (Somewhat anonymized):

<XXX>
        <Code A="oa  ">01</Code>
        <Name A="oa  ">Card</Name>
        <F1 A="oa  ">x</F1>
        <F2 A="oa  ">y</F2>
        <F3 A="oa  ">z</F3>
</XXX>

I load the XML-document into a XElement and query it with linq

var query = from creditcard in xml.Descendants("XXX")
                    where creditcard.Element("Code").Value == "1"
                    select new
                    {
                        Id = Convert.ToInt32(creditcard.Element("Code").Value),
                        Description = creditcard.Element("Name").Value,
                        xx = creditcard.Element("F1").Value,
                        yy = creditcard.Element("F2").Value,
                        zz = creditcard.Element("F3").Value
                    };

This will result in a empty set when I dump the query in LinqPad. However if I change the where clause to:

where Convert.ToInt32(creditcard.Element("Code").Value) == 1

Then it will correctly find the item in question. Any ideas why it works this way or what I have missed?

EDIT: Sorry, I missed to change a "Kod" to Code as I changed it for posting. Fixed now.

+4  A: 

Because the value is "01", not "1". Converting to Int32 masks this difference.

Matthew Flaschen
I feel like a god damn retard now. Thank you so much.
cc81
A: 

As your first comparaison is made on string, you try to compare "01" with "1", which is obviously not the same. By converting "01" to an integer value, you get an int with a value = 1, so your comparaison is right this time.

Shimrod
A: 

The query does not work as you will have to process siblings not child elements.

Your query works for:

<XXX>
    <Code>
        <Kod A="oa  ">01</Kod>
        <Name A="oa  ">Card</Name>
        <F1 A="oa  ">x</F1>
        <F2 A="oa  ">y</F2>
        <F3 A="oa  ">z</F3>
    </Code >
</XXX>

But even then only if you modify

where creditcard.Element("Code").Value == "1"

to

where creditcard.Element("Code").Element("Kod").Value == "01"
Obalix