What's the best way to get the contents of the mixed body
element in the code below? The element might contain either XHTML or text, but I just want its contents in string form. The XmlElement
type has the InnerXml
property which is exactly what I'm after.
The code as written almost does what I want, but includes the surrounding <body>
...</body>
element, which I don't want.
XDocument doc = XDocument.Load(new StreamReader(s));
var templates = from t in doc.Descendants("template")
where t.Attribute("name").Value == templateName
select new
{
Subject = t.Element("subject").Value,
Body = t.Element("body").ToString()
};
I think this is a much better method (in VB, shouldn't be hard to translate):
Given an XElement x:
Is it possible to use the System.Xml namespace objects to get the job done here instead of using LINQ? As you already mentioned, XmlNode.InnerXml is exactly what you need.
@Greg: It appears you've edited your answer to be a completely different answer. To which my answer is yes, I could do this using System.Xml but was hoping to get my feet wet with LINQ to XML.
I'll leave my original reply below in case anyone else wonders why I can't just use the XElement's .Value property to get what I need:
@Greg: The Value property concatenates all the text contents of any child nodes. So if the body element contains only text it works, but if it contains XHTML I get all the text concatenated together but none of the tags.
doc.ToString() or doc.ToString(SaveOptions) does the work. See http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.tostring(v=vs.110).aspx
Will do the job for you