问题是用于创建 XElement 的 XName 需要指定正确的命名空间。我想做的是创建一个像这样的静态类:-
public static class XHtml
{
public static readonly XNamespace Namespace = "http://www.w3.org/1999/xhtml";
public static XName Html { get { return Namespace + "html"; } }
public static XName Body { get { return Namespace + "body"; } }
//.. other element types
}
现在您可以像这样构建一个 xhtml 文档:-
XDocument doc = new XDocument(
new XElement(XHtml.Html,
new XElement(XHtml.Body)
)
);
该静态类的另一种方法是:-
static class XHtml
{
public static readonly XNamespace Namespace = "http://www.w3.org/1999/xhtml";
public static readonly XName Html = Namespace + "html";
public static readonly XName Body = Namespace + "body";
}
无论您是否使用它们,这都有实例化所有可能的 XName 的缺点,但优点是命名空间 +“标记名”的转换只发生一次。我不确定这种转换是否会被优化。我确信 XNames 只被实例化一次:-
XNamepace n = "http://www.w3.org/1999/xhtml";
XNames x = n + "A";
XName y = n + "A";
Object.ReferenceEquals(x, y) //is true.