gpt4 book ai didi

xml - 使用 LINQ to XML 将 HTML 标记保留在 XML 中

转载 作者:数据小太阳 更新时间:2023-10-29 01:54:46 25 4
gpt4 key购买 nike

我有一个 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>

我正在使用以下查询从文件中提取“提示”:

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

我遇到的问题是 Html 元素被删除了。我希望使用 InnerHtml 之类的东西来代替 Value,但似乎不存在。

有什么想法吗?

提前致谢

戴夫

最佳答案

调用 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());
}

这样您将获得 HTML 元素及其后代和散布的文本节点。我强烈怀疑它基本上等同于 InnerXml。

关于xml - 使用 LINQ to XML 将 HTML 标记保留在 XML 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/457970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com