我正在使用新的 System.Xml.Linq 创建 HTML 文档(是的,我知道 HtmlDocument,但更喜欢 XDocument/XElement 类)。我在插入
(或任何其他 HTML 实体)时遇到问题。我已经尝试过的:
直接将文本放入是行不通的,因为 & 会变成 int &。
new XElement("h1", "Text to keep together.");
我尝试使用以下方法解析原始 XML,但出现此错误:
XElement.Parse("要放在一起的文本。");
--> 引用未声明的实体“nbsp”。`
第三个尝试如下所示。如果我保存到一个文件,只有一个空格,
var X = new XDocument(new XElement("Name", KeepTogether("Hi Mom!")));
private static XNode KeepTogether(string p)`
{
return XElement.Parse("<xml>" + p.Replace(" ", " ") + "</xml>").FirstNode;
}
我找不到一种方法可以在不转义的情况下推送原始文本。我是否遗漏了一些明显的东西?
最佳答案
I couldn't find a way to just shove the raw text through without it getting escaped.
只需将 Unicode 字符放在那个 直接在文本节点中引用 (U+00A0 NO-BREAK SPACE),然后让序列化程序担心它是否需要转义为 或不。 (可能不是:如果您使用 UTF-8 或 ISO-8859-1 作为页面编码,则可以直接包含该字符,而不必担心将其编码为实体引用或字符引用)。
new XElement("h1", "Text\u00A0to\u00A0keep\u00A0together");
关于c# - 使用 XElement 时如何输入文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/587547/