我如何强制XmlWriter正确处理名称空间?

我想用XmlWriter来写这样的东西(全部在一个名字空间中):

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

但最接近我似乎得到的是这样的:

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

使用此代码:

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

当我没有指定前缀时,我得到:

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

在重复命名空间中生成这些“幻影”前缀会在整个生成的文档(p3,p4,p5等)中生成。

当我不写属性时,我得到我想要的输出(显然,它缺少属性)。

为什么XmlWriter不像我问的那样省略重复的命名空间?


像这样尝试:

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();
        }
    }
}
链接地址: http://www.djcxy.com/p/54211.html

上一篇: How can I coerce XmlWriter to handle namespaces correctly?

下一篇: Adding Core Data to iPhone app with existing (plain) models