0

How do you parse this kind of XML file with LINQ?

<houses>
  <house nbr="146" city="Linköping" owner="john"/>
  <house nbr="134" city="Norrköping" owner="wayne"/>
  <house nbr="146" city="Köping" owner="steffe"/>
</houses>

All examples I can find only describe how to parse when each element has a value.

If this was the case I would have done it like this:

var houses = from house in xmlDoc.Descendants("house")
            select new RowData
            {
                number = spec.Element("nbr").Value,
                city = spec.Element("city").Value,
                owner = spec.Element("owner").Value,
            };
return houses ;

But this xml file is not formatted that way.

2
  • What are you looking to get out of it? Commented Nov 11, 2012 at 15:30
  • Each element provides a collection of attributes that you can use in a LINQ query. Show us how you read the elements in your code. Commented Nov 11, 2012 at 15:36

1 Answer 1

1

Try this:

var houses = from house in document.Descendants("house")
                select new RowData
                {
                    number = (int)house.Attribute("nbr"),
                    city = (string)house.Attribute("city"),
                    owner = (string)house.Attribute("owner")
                };
Sign up to request clarification or add additional context in comments.

Comments

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.