6

给定以下代码:

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与 Root 元素具有相同命名空间的属性?

这种代码(XmlSchemaForm.Unqualified部分)是由WSCF.blue工具生成的,它与命名空间混淆了。

4

1 回答 1

0

You can override namespace specified in the element type. E.g. you can have

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

And the output would be

<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>

Microsoft's implementation of Form = XmlSchemaForm.Unqualified appears to be exactly equivalent to setting Namespace to "". In particular, it cannot be used if you explicitly specified any other namespace (MSDN reference). If you do, you will get this exception:

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.

于 2013-07-05T22:41:48.977 回答