获得XElement的InnerXml的最佳方法是什么?

body在下面的代码中获取混合元素内容的最佳方法是什么?该元素可能包含XHTML或文本,但我只想要其字符串形式的内容。该XmlElement类型具有InnerXml我正在追求的属性。


编写的代码几乎可以实现我想要的功能,但包含了我不想要的周围的<body>... </body>元素。


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()

                };


沧海一幻觉
浏览 500回答 3
3回答

陪伴而非守候

我认为这是一个更好的方法(在VB中,不应该难以翻译):给定XElement x:Dim xReader = x.CreateReaderxReader.MoveToContentxReader.ReadInnerXml

吃鸡游戏

如何在XElement上使用这个“扩展”方法?为我工作!public static string InnerXml(this XElement element){&nbsp; &nbsp; StringBuilder innerXml = new StringBuilder();&nbsp; &nbsp; foreach (XNode node in element.Nodes())&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // append node's xml string to innerXml&nbsp; &nbsp; &nbsp; &nbsp; innerXml.Append(node.ToString());&nbsp; &nbsp; }&nbsp; &nbsp; return innerXml.ToString();}或者使用一点Linqpublic static string InnerXml(this XElement element){&nbsp; &nbsp; StringBuilder innerXml = new StringBuilder();&nbsp; &nbsp; doc.Nodes().ToList().ForEach( node => innerXml.Append(node.ToString()));&nbsp; &nbsp; return innerXml.ToString();}注意:上面的代码必须使用element.Nodes()而不是element.Elements()。记住两者之间的区别非常重要。element.Nodes()给你一些像XText,XAttribute等等,但XElement只有一个元素。
打开App,查看更多内容
随时随地看视频慕课网APP