0

I'm trying to bind the contents of the following file using LINQ but having issues with the syntax.

<metadefinition>
  <page>
    <name>home</name>
    <metas>
      <meta>
        <metaname>
          title
        </metaname>
        <metavalue>
          Welcome Home
        </metavalue>
      </meta>

      <meta>
        <metaname>
          description
        </metaname>
        <metavalue>
          Welcome Home Description
        </metavalue>
      </meta>

    </metas>
  </page>

  <page>
    <name>results</name>
    <metas>
      <meta>
        <metaname>
          title
        </metaname>
        <metavalue>
          Welcome to Results
        </metavalue>
      </meta>
    </metas>
  </page>
</metadefinition>

My query looks like this but as you can see it is missing the retrieval of the metas tag. How do I accomplish this?

 var pages = from p in xmlDoc.Descendants(XName.Get("page"))
                            where p.Element("name").Value == pageName
                            select new MetaPage
                            {
                                Name = p.Element("name").Value,
                                MetaTags = p.Elements("metas").Select(m => new Tag { MetaName = m.Element("metaname").Value.ToString(),
                                                                                     MetaValue = m.Element("metacontent").Value.ToString()
                                }).ToList()
                            };
1
  • 2
    It's a little unclear what exactly you are trying to accomplish here. What do you mean by "it is missing the retrieval of the metas tag"? Commented Feb 22, 2012 at 8:56

1 Answer 1

1

If <metadefinition> is a root element, then there is no need for iterating over all descendants of the document, that's way too inefficient.

var pages = from p in xmlDoc.Root.Elements("page")
            where p.Element("name").Value == pageName
            select new MetaPage {
                Name = p.Element("name").Value,
                MetaTags = p.Element("metas").Elements("meta").Select(m=>new Tag{
                    MetaName = m.Element("metaname").Value.ToString(),
                    MetaValue = m.Element("metavalue").Value.ToString()
                }).ToList()
            };
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.