Search code examples
c#-4.0linq-to-xmlstringwriter

add header to the XDocument, and schema


I want to have xml like

<?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>

so I use the following code

   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());

but it crash in save saying

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

Solution

  • I used the following and worked well

     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)
    
                    )
    
                        );
    

    and it worked very well