Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I coerce XmlWriter to handle namespaces correctly?

I want to use XmlWriter to write something like this (all in one namespace):

<Root xmlns="http://tempuri.org/nsA">
  <Child attr="val" />
</Root>

but the closest I can seem to get is this:

<p:Root xmlns:p="http://tempuri.org/nsA">
  <p:Child p:attr="val" />
</p:Root>

using this code:

using System;
using System.Text;
using System.Xml;

namespace ConsoleApplication1
{
    internal class Program
    {
        private const string ns = "http://tempuri.org/nsA";
        private const string pre = "p";

        private static void Main(string[] args)
        {
            var sb = new StringBuilder();
            var settings = new XmlWriterSettings
                     {
                       NamespaceHandling = NamespaceHandling.OmitDuplicates, 
                                             /* ineffective */             
                       Indent = true
                     };
            using (XmlWriter writer = XmlWriter.Create(sb, settings))
            {
                writer.WriteStartElement(pre, "Root", ns);
                writer.WriteStartElement(pre, "Child", ns);
                writer.WriteAttributeString(pre, "attr", ns, "val"); 
                                             // breaks namespaces    
                writer.WriteEndElement();
                writer.WriteEndElement();
            }
            Console.WriteLine(sb.ToString());
        }
    }
}

When I don't specify a prefix, I get:

<Root xmlns="http://tempuri.org/nsA">
  <Child p2:attr="val" xmlns:p2="http://tempuri.org/nsA" />
</Root>

The generation of these "phantom" prefixes in duplicate namespaces occurs throughout the generated document (p3, p4, p5 etc).

When I don't write attributes, I get the output I want (except it's missing the attributes, obviously).

Why isn't XmlWriter omitting duplicate namespaces like I asked?

like image 244
lesscode Avatar asked Aug 09 '11 15:08

lesscode


1 Answers

Try like this:

using System;
using System.Text;
using System.Xml;

class Program
{
    private const string ns = "http://tempuri.org/nsA";

    static void Main()
    {
        var settings = new XmlWriterSettings
        {
            Indent = true
        };
        using (var writer = XmlWriter.Create(Console.Out, settings))
        {
            writer.WriteStartElement("Root", ns);
            writer.WriteStartElement("Child");
            writer.WriteAttributeString("attr", "", "val");
            writer.WriteEndElement();
            writer.WriteEndElement();
        }
    }
}
like image 100
Darin Dimitrov Avatar answered Oct 21 '22 17:10

Darin Dimitrov