如何创建的XElement为儿童默认命名空间,而不在所有子节点使用的XNamespace [英] How to create XElement with default namespace for children without using XNamespace in all child nodes
问题描述
我试图使用 System.Xml.Linq的
以创建XHTML文档。因此,节点在我的树木绝大多数应该使用此命名空间:
I'm trying to use System.Xml.Linq
to create XHTML documents. Thus, the vast majority of the nodes in my trees ought to use this namespace:
http://www.w3.org/1999/xhtml
我可以创建的XElement
节点作用于这个命名空间很轻松了,使用的XNamespace
,像这样的:
I can create XElement
nodes scoped to this namespace easily enough, using an XNamespace
, like this:
XNamespace xhtml = "http://www.w3.org/1999/xhtml";
// ...
new XElement(xhtml + "html", // ...
不过,我不希望有作出的XNamespace
可在所有的code创建HTML节点,并以preFIX每单个的XElement
(和 XAttribute
)创建相应的名字。
However, I don't want to have to make an XNamespace
available throughout all the code that creates HTML nodes, and have to prefix every single XElement
(and XAttribute
) name I create accordingly.
的XML文本格式本身需要这个要求考虑在内,并允许设置一个默认的命名空间中,由后代继承了祖先,使用预留的xmlns
属性。我想用做同样的事情 System.Xml.Linq的
。
The XML text format itself takes this requirement into account, and permits setting a default namespace in an ancestor which is inherited by descendants, using the reserved xmlns
attribute. I'd like to do something similar using System.Xml.Linq
.
这可能吗?
推荐答案
我已经决定使用一个静态类名为 XHTML
,如下所示:
I've decided to use a static class called XHtml
, that looks like this:
public static class XHtml
{
static XHtml()
{
Namespace = "http://www.w3.org/1999/xhtml";
}
public static XNamespace Namespace { get; private set; }
public static XElement Element(string name)
{
return new XElement(Namespace + name);
}
public static XElement Element(string name, params object[] content)
{
return new XElement(Namespace + name, content);
}
public static XElement Element(string name, object content)
{
return new XElement(Namespace + name, content);
}
public static XAttribute Attribute(string name, object value)
{
return new XAttribute(/* Namespace + */ name, value);
}
public static XText Text(string text)
{
return new XText(text);
}
public static XElement A(string url, params object[] content)
{
XElement result = Element("a", content);
result.Add(Attribute("href", url));
return result;
}
}
这似乎是做事最干净的方法,特别是因为我可以再添加的便利程序,如 XHtml.A
办法(不是所有我的班此处示出)。
This seems to be the cleanest way of doing things, particularly as I can then add in convenience routines, such as the XHtml.A
method (not all of my class is shown here).
这篇关于如何创建的XElement为儿童默认命名空间,而不在所有子节点使用的XNamespace的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!