C# - 向文档添加XML命名空间(xmlns)标签

7

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

我已经接近完成,但是我需要在我的文档顶部添加类似以下的内容:

<ABC xmlns="http://www.acme.com/ABC" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" fileName="acmeth.xml" date="2011-09-16T10:43:54.91+01:00" origin="TEST" ref="XX_88888">

我需要在我现有内容下方添加以下内容:

我需要在现有的内容下方添加以下内容:

<?xml version="1.0" encoding="UTF-8"?>

我使用以下代码创建这个东西:
XmlWriterSettings settings = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true };

在这之后,我继续创建我的XML文档,现在已经完成,但我需要添加这个中间部分。
谢谢。
约翰

也许我漏掉了什么,但问题是什么? - CodingGorilla
请展示您当前的代码,至少包括创建根元素的代码。 - John Saunders
2个回答

22

我认为这就是你想要的:

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); 
    }
}

new XAttribute("xmlns", ns.NamespaceName) 是必要的吗?因为在上一行中已经设置了元素的默认命名空间,不是吗? - spender
@spender:好的,我们正在设置元素的命名空间 - 但我们没有明确设置默认命名空间。在这种情况下似乎可以正常工作,但个人而言,我宁愿明确说明。 - Jon Skeet

8
您可以像这样向XmlDocument的根元素添加命名空间声明:
document.DocumentElement.SetAttribute("xmlns", "http://default-namespace");
document.DocumentElement.SetAttribute("xmlns:ns2", "http://other-namespace");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接