无法在命名空间中输出没有前缀的xml文档

时间:2013-12-24 04:47:05

标签: xml xml-namespaces

我使用C#和XElement从Sql Server数据创建xml文档,客户端规范要求主标记中的属性名称空间为xmlns(case是主标记)。 以下是他们的规范中的示例:

<case techname="Client" count="4" xmlns="http://tempuri.org/NBAppSchema.xsd">

我的问题是我在C#中遇到错误,试图使用前缀输出这个'case'标签的xmlns属性。 (错误:前缀''无法在同一个开始元素标记内从''重新定义为'http://example.com/xmlns1'。)

当我包含前缀时,它会生成xml,只有客户端告诉我,当他们尝试加载它时,它会出错。 带前缀的示例:

<case techname="Client" count="4" xmlns:prfx="http://tempuri.org/NBAppSchema.xsd">

代码:

XNamespace ns = "http://tempuri.org/NBAppSchema.xsd";
XElement mainCaseTag = new XElement("case", new XAttribute("techname", "Univers"), new XAttribute("count", totalApplicationCount), new XAttribute(XNamespace.Xmlns + "prfx", ns));

我想输出此属性作为没有前缀的第一个示例。 我试图研究,但无法找到或理解如何使用没有前缀的命名空间输出此xml文件。

1 个答案:

答案 0 :(得分:1)

试试这个:

XNamespace ns = "http://tempuri.org/NBAppSchema.xsd";      
var doc2 = new XDocument(
    new XElement(ns + "root",
        new XAttribute("attr1", "val1"), 
        new XElement(ns + "SubNode")));
Console.WriteLine(doc2.ToString());

demo有两个选项。