在 XElement 上使用这个“扩展”方法怎么样?为我工作!
public static string InnerXml(this XElement element)
{
StringBuilder innerXml = new StringBuilder();
foreach (XNode node in element.Nodes())
{
// append node's xml string to innerXml
innerXml.Append(node.ToString());
}
return innerXml.ToString();
}
或者使用一点 Linq
public static string InnerXml(this XElement element)
{
StringBuilder innerXml = new StringBuilder();
doc.Nodes().ToList().ForEach( node => innerXml.Append(node.ToString()));
return innerXml.ToString();
}
注意:上面的代码必须使用 element.Nodes()
而不是 element.Elements()
。记住两者之间的区别非常重要。 element.Nodes()
给你所有的东西,比如 XText
、XAttribute
等等,但 XElement
只是一个元素。