tags:

views:

262

answers:

3

Hi

I have a basic xml file that looks like this.

    <root>
     <item>
        <title><p>some title</p></title>
     </item>
    ...
    </root>

What I want, is to get the whole title string including the html tag of the xml using linq and displaying it in a repeater . I can get the title with no problem, but the <p> tag is being stripped out.

If I use
title = item.Element("title").ToString(), it works somehow but I get all the xml tag as well - meaning the title is not displayed in html.

I already tried with encoding the "<" with "&lt;" but to do this makes the xml hard to read.

What would be a possible solution besides using CDATA and encoding?

Cheers Terry

+1  A: 

Create a reader from the title element and read InnerXml:

    static void Main(string[] args)
    {
        string xml = "<root><item><title><p>some title</p></title></item></root>";

        XDocument xdoc = XDocument.Parse(xml);
        XElement te = xdoc.Descendants("title").First();
        using (XmlReader reader = te.CreateReader())
        {
            if (reader.Read())
                title = reader.ReadInnerXml();
        }
    }
bruno conde
thanks bruno for the suggestion, unfortunately it didn't work. Could you give me an example of how I would combine this with the linq select statement I'm using? - Terry
Terry Marder
I updated the code. You have a complete example.
bruno conde
thanks bruno, you pointed me in the right direction. Will take a little time to adapt it to my needs, but now I know where to start.
Terry Marder
A: 

See http://stackoverflow.com/questions/3793/best-way-to-get-innerxml-of-an-xelement for some ideas on how to get the "InnerXml" of an XElement.

Steve Guidi
A: 

XElement x = XElement.Parse(your xml);

var y= x.Descendants("title").Descendants();

Then iterate y for a list of the contents of the title elements.

BTW, LINQPad (http://www.linqpad.net) is a handy free tool for trying out LINQ-XML.

ebpower
Hi ebpower, I tried that but somehow couldn't get it to work. Thanks for the hint with LINQPad, I had totally forgotten about it, been a while since I worked with it.
Terry Marder
Hmm - i pasted from my LINQPad window. I used "<root><item><title><p>some title</p></title></item></root>" in place of the "your xml" parameter to XElement.Parse.
ebpower