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

JMK*_*JMK 6 c# xml namespaces xml-namespaces

我正在使用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">
Run Code Online (Sandbox Code Playgroud)

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

<?xml version="1.0" encoding="UTF-8"?>
Run Code Online (Sandbox Code Playgroud)

我使用以下代码创建它:

XmlWriterSettings settings = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true };
Run Code Online (Sandbox Code Playgroud)

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

谢谢

约翰

Jon*_*eet 20

我想这就是你所追求的:

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); 
    }
}
Run Code Online (Sandbox Code Playgroud)


Eli*_*ing 5

您可以将命名空间声明添加到这样的根元素XmlDocument:

document.DocumentElement.SetAttribute("xmlns", "http://default-namespace");
document.DocumentElement.SetAttribute("xmlns:ns2", "http://other-namespace");
Run Code Online (Sandbox Code Playgroud)