将标头添加到XDocument和架构

时间:2012-10-22 10:04:31

标签: c#-4.0 linq-to-xml stringwriter

我希望xml像

<?xml version="1.0"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schema.test.com/test">

<test1>1</test1>
.
.
.
.
<test9>9</test9>
</root>

所以我使用以下代码

   Dictionary<string, object> Data = new Dictionary<string, object>();
for (int i = 0; i < 10; i++)
            {
                Data.Add("Test" + i, i);



            }

            Console.WriteLine(DateTime.Now.ToShortTimeString());


            XNamespace xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
            XNamespace xsd = XNamespace.Get("http://www.w3.org/2001/XMLSchema");
            XNamespace xsd1 = XNamespace.Get("http://schema.test.com/test");


            XDocument doc = new XDocument(

                new XDeclaration("1.0", "utf-16", "yes"),

                new XElement(

                    "root",
                    new XAttribute(XNamespace.Xmlns + "xsi", xsi),
                    new XAttribute(XNamespace.Xmlns + "xsd", xsd),
                    new XAttribute(XNamespace.None + "xmlns", xsd1),

                from p in Data select new XElement(p.Key, p.Value )

                )

                    );

            /*  XmlSchema schema = new XmlSchema();
              schema.Namespaces.Add("xmlns", "http://schema.medstreaming.com/report");

              doc.Add(schema);*/


            var wr = new StringWriter();
            doc.Save(wr);
            Console.Write(wr.GetStringBuilder().ToString());

但是在保存说法中崩溃了

The prefix '' cannot be redefined from '' to 'http://schema.test.com/test' within the same start element tag.

2 个答案:

答案 0 :(得分:4)

我使用以下内容并且运作良好

 XNamespace xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
            XNamespace xsd = XNamespace.Get("http://www.w3.org/2001/XMLSchema");
            XNamespace ns = XNamespace.Get("http://schema.test.com/test");


            XDocument doc = new XDocument(

                new XDeclaration("1.0", "utf-8", "yes"),

                new XElement(

                    ns + "root",
                    new XAttribute("xmlns", ns.NamespaceName),
                    new XAttribute(XNamespace.Xmlns + "xsd", xsd.NamespaceName),
                    new XAttribute(XNamespace.Xmlns + "xsi", xsi.NamespaceName),
                    from p in Data select new XElement(ns + p.Key, p.Value)

                )

                    );

并且效果很好

答案 1 :(得分:1)

由于您要重新定义全局xml命名空间,因此需要在标准xmlns属性前加上您定义的新前缀。

变化:

new XAttribute(XNamespace.None + "xmlns", xsd1),

为:

new XAttribute(xsd + "xmlns", xsd1),

它应该排序。