使用LINQ to XML将HTML标记保存在XML中

Dav*_*uge 5 xml linq linq-to-xml

我有一个xml文件,我使用LINQ to XML从中提取html.这是该文件的示例:

<?xml version="1.0" encoding="utf-8" ?>
<tips>
    <tip id="0">
    This is the first tip.
</tip>
<tip id="1">
    Use <b>Windows Live Writer</b> or <b>Microsoft Word 2007</b> to create and publish content.
</tip>
<tip id="2">
    Enter a <b>url</b> into the box to automatically screenshot and index useful webpages.
</tip>
<tip id="3">
    Invite your <b>colleagues</b> to the site by entering their email addresses.  You can then share the content with them!
</tip>
</tips>
Run Code Online (Sandbox Code Playgroud)

我使用以下查询从文件中提取"提示":

Tip tip = (from t in tipsXml.Descendants("tip")
                   where t.Attribute("id").Value == nextTipId.ToString()
                   select new Tip()
                   {
                     TipText= t.Value,
                     TipId = nextTipId
                   }).First();
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是Html元素被剥离了.我希望使用像InnerHtml这样的东西代替Value,但这似乎并不存在.

有任何想法吗?

提前全部谢谢,

戴夫

Jon*_*eet 8

打电话t.ToString()而不是Value.这将把XML作为字符串返回.您可能希望使用带有SaveOptions的重载来禁用格式化.我现在无法检查,但我怀疑它将包含元素标签(和元素),因此您需要将其剥离.

请注意,如果您的HTML不是有效的XML,则最终会得到无效的整体XML文件.

XML文件的格式是否完全不受您的控制?任何HTML内部都可以更好地进行XML编码.

编辑:避免获取外部部分的一种方法可能是做这样的事情(当然是从查询调用的单独方法):

StringBuilder builder = new StringBuilder();
foreach (XNode node in element.Nodes())
{
    builder.Append(node.ToString());
}
Run Code Online (Sandbox Code Playgroud)

这样,您将获得带有后代和散布文本节点的HTML元素.基本上它相当于InnerXml,我强烈怀疑.