Bar*_*lly 9 .net c# xml namespaces linq-to-xml
我正在尝试用来System.Xml.Linq创建XHTML文档.因此,我树中的绝大多数节点都应该使用这个命名空间:
http://www.w3.org/1999/xhtml
Run Code Online (Sandbox Code Playgroud)
我可以XElement很容易地创建作用于此命名空间的节点,使用XNamespace如下:
XNamespace xhtml = "http://www.w3.org/1999/xhtml";
// ...
new XElement(xhtml + "html", // ...
Run Code Online (Sandbox Code Playgroud)
但是,我不希望XNamespace在创建HTML节点的所有代码中都可用,并且必须为我创建的每个XElement(和XAttribute)名称添加前缀.
XML文本格式本身考虑了这一要求,并允许使用reserved xmlns属性在后代继承的祖先中设置默认命名空间.我想做类似的事情System.Xml.Linq.
这可能吗?
我决定使用一个名为的静态类XHtml,如下所示:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这似乎是最干净的做事方式,特别是当我可以添加方便例程时,例如XHtml.A方法(这里没有显示我的所有类).
| 归档时间: |
|
| 查看次数: |
15694 次 |
| 最近记录: |