C#-将XML名称空间(xmlns)标记添加到文档
我正在使用C#中的System.XML创建一个XML文档 我几乎完成了,但我需要在文档顶部添加一些类似的内容:C#-将XML名称空间(xmlns)标记添加到文档,c#,xml,namespaces,xml-namespaces,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"> 在这之后,我继续
<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文档,现在已经完成了,但我需要在两者之间添加它
谢谢
约翰我想这就是你想要的:
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");
也许我遗漏了什么,但问题是什么?请显示您当前的代码,至少是创建根元素的代码。
newxattribute(“xmlns”,ns.NamespaceName)
是否有必要?您已经在上面的行中设置了元素的默认名称空间,不是吗?@spender:我们正在设置元素的名称空间,但没有显式设置默认名称空间。在这种情况下,没有它似乎是可行的,但就我个人而言,我宁愿直截了当。
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);
}
}
document.DocumentElement.SetAttribute("xmlns", "http://default-namespace");
document.DocumentElement.SetAttribute("xmlns:ns2", "http://other-namespace");