Pit Digger
Pit Digger

Reputation: 9800

Selecting HTML Content of a node LINQ XML

I have XML like this

  <component>
        <section>
          <title>Reporting Parameters</title>
          <text>
            <list>
              <item>Reporting period: January 1st, 2012
            </list>
          </text>
       </section>
   </component>

I want to select entire content of node including etc. elements but it selects only plain text "Reporting period: January 1st, 2012" , Reason is that it might content some HTML markup which I need to store in database, I am using following query

  var components = (from c in cdafile.Root.Elements(ns + "component")
                  select new{
                      name = (string)c.Element(ns + "section").Element(ns + "title").Value,
                      text = (string)c.Element(ns + "section").Element(ns + "text"),
                  });

Upvotes: 1

Views: 504

Answers (1)

k.m
k.m

Reputation: 31484

Explicit cast operator is overloaded for XElement (to return concatenated, inner text of nodes), use .ToString() to get nodes content:

text = c.Element(ns + "section").Element(ns + "text").ToString()

And to get children markup only:

text = string.Join(Environment.NewLine, c
    .Element(ns + "section").Element(ns + "text")
    .Elements().Select(e => e.ToString())
)

Upvotes: 1

Related Questions