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?
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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With