Monday, April 11, 2011

How do I add a namespace while doing XmlSerialization with an XmlWriter?

I am using the XmlWriter in conjunction with Xml Serialization. I am able to output the XML fine, but how to include the xmlns attribute with the XmlWriter seems to be escaping me.

To write the start of the document I use the following:

    Writer.WriteStartDocument();
    Writer.WriteStartElement("urlset","http://www.sitemaps.org/schemas/sitemap/0.9");

With my XmlWriter created I then loop through SitemapNodes I have created them and write them to the underlying stringbuilder through serialization like this:

    foreach (uk.co.andrewrea.SitemapNode node in List)
    {
        Serializer.Serialize(Writer, node);
    }

As I say this works fine BUT the above namespace for the root element is not included. Every time I try to physically write the attribute, xmlns, I get an exception that the xmlns is reserved by the system for XML use, so basically I cannot use.

I know how to do this using the XmlTextWriter and also using the XmlDocument class but i need to understand how I achieve this using the XmlWriter and through Serialization.

The following attempt also throws the exception about that namespace being reserved.

foreach (uk.co.andrewrea.SitemapNode node in List)
{
      XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
      ns.Add("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");

      Serializer.Serialize(Writer, node, ns);
}

Exception Details: System.ArgumentException: Prefix "xmlns" is reserved for use by XML.
From stackoverflow
  • You can add the namespace to the XmlSerialization attributes, e.g.:

    [XmlElement(
    ElementName = "Members",
    Namespace = "http://www.cpandl.com")]
    public Employee[] Employees;
    

    if you have control over the code.

    REA_ANDREW : I have included that now, but still the attribute is not output.
    REA_ANDREW : Right I am being DUMB, I was viewing the output in firefox, WHICH hides these attibutes. Viewing the source showed that my oriignal code actually works fine. :-( Thanks for your help.

0 comments:

Post a Comment