C# – 将XML命名空间(xmlns)标记添加到文档

我正在使用C#中的System.XML创建XML文档。

我差不多完成了,但我需要在文档的顶部添加一些类似的内容:

 

我需要在下面的地方添加:

  

我使用以下代码创建它:

 XmlWriterSettings settings = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true }; 

在此之后,我继续创建我的XML文档,现在已经完成,但我需要在中间添加它。

谢谢

约翰

我想这就是你所追求的:

 using System; using System.Xml.Linq; class Test { static void Main() { XNamespace ns = "http://www.acme.com/ABC"; DateTimeOffset date = new DateTimeOffset(2011, 9, 16, 10, 43, 54, 91, TimeSpan.FromHours(1)); XDocument doc = new XDocument( new XElement(ns + "ABC", new XAttribute("xmlns", ns.NamespaceName), new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"), new XAttribute("fileName", "acmeth.xml"), new XAttribute("date", date), new XAttribute("origin", "TEST"), new XAttribute("ref", "XX_88888"))); Console.WriteLine(doc); } } 

您可以将命名空间声明添加到XmlDocument的根元素,如下所示:

 document.DocumentElement.SetAttribute("xmlns", "http://default-namespace"); document.DocumentElement.SetAttribute("xmlns:ns2", "http://other-namespace");