2013-02-12 96 views
9

我想:如何为XDocument指定xmlns?

textBox1.Text = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), 
    new XElement("root1", new XAttribute("xmlns", @"http://example.com"), new XElement("a", "b")) 
).ToString(); 

,但我得到:

The prefix '' cannot be redefined from '' to 'http://example.com' within the same start element tag. 

我也试过用(根据一个答案,我发现):

XAttribute(XNamespace.Xmlns,... 

但得到了一个错误,以及。

注意:我不想在文档中有多个xmlns。

+2

也许这个工作适合你:http://stackoverflow.com/a/2874572/1373170 – 2013-02-12 20:07:56

回答

20

XDocument API与名称空间范围名称一起使用的方式为XName实例。只要您接受XML名称不只是一个字符串,而是一个范围标识符,这些工作就相当容易。下面是我如何做到这一点:

var ns = XNamespace.Get("http://example.com"); 
var doc = new XDocument(new XDeclaration("1.0", "utf-8", null)); 
var root = new XElement(ns + "root1", new XElement(ns + "a", "b")); 
doc.Add(root); 

结果:

<root1 xmlns="http://example.com"> 
    <a>b</a> 
</root1> 

注意+运算符重载,以接受XNamespaceString导致和XName实例。

+1

谢谢。看起来很奇怪,不会有一种简单的方法来只添加一次命名空间。 – ispiro 2013-02-12 20:50:35

+1

嗯,我认为这非常简单,它真正驱动回家,你正在做的是创建命名空间名称,而不仅仅是字符串。如果你想为命名空间减少代码,'System.Xml.XmlDocument'类使用命名空间管理器来跟踪根命名空间,并且你可以假装它不存在,一旦你设置正确。 – codekaizen 2013-02-12 20:53:35

+0

看到我的下一个问题:http://stackoverflow.com/questions/14841517/how-can-i-add-innerxml-without-it-being-modified-in-any-way - 我想'XmlDocument'作为好,并没有帮助。 – ispiro 2013-02-12 20:55:16