给出以下代码:

using System;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace XmlSerializationTest
{
    [XmlType(Namespace = "http://www.test.com")]
    public class Element
    {
        [XmlElement]
        public int X;
    }

    [XmlRoot(Namespace = "http://www.test.com")]
    public class Root
    {
        [XmlElement(Form = XmlSchemaForm.Unqualified)]
        public Element Element;
    }

    public static class Program
    {
        public static void Main(string[] args)
        {
            var root = new Root { Element = new Element { X = 1 } };
            var xmlSerializer = new XmlSerializer(typeof(Root));
            xmlSerializer.Serialize(Console.Out, root);
        }
    }
}

输出为:
<?xml version="1.0" encoding="ibm852"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.test.com">
  <Element xmlns="">
    <X xmlns="http://www.test.com">1</X>
  </Element>
</Root>

问题是,为什么将form属性设置为XmlSchemaForm.Unqualified会导致Element元素的命名空间设置为""即使它的XmlTypeAttribute属性与根元素具有相同的命名空间?
这类代码(即XmlSchemaForm.Unqualified部分)是由WSCF.blue工具生成的,它正在扰乱名称空间。

最佳答案

可以重写元素类型中指定的命名空间。你可以

[XmlElement(Namespace="http://foo.com")]
public Element Element;

结果是
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.test.com">
  <Element xmlns="http://foo.com">
    <X xmlns="http://www.test.com">1</X>
  </Element>
</Root>

微软对Form = XmlSchemaForm.Unqualified的实现似乎完全等同于将Namespace设置为""。特别是,如果显式指定了任何其他命名空间(MSDN reference),则无法使用它。如果这样做,您将得到以下异常:
Unhandled Exception: System.InvalidOperationException: There was an error reflecting type 'XmlSerializationTest.Root'. ---> System.InvalidOperationException: There was an error reflecting field 'Element'. ---> System.InvalidOperationException: The Form property may not be 'Unqualified' when an explicit Namespace property is present.

09-11 20:36