[英]C# - Add XML Namespace (xmlns) tag to document
我正在使用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文檔,現在已完成但我需要在中間添加它。
謝謝
約翰
我想這就是你所追求的:
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");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.