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>

問題は、フォーム プロパティを設定すると、ルート要素と同じ名前空間を持つ属性がある場合でもXmlSchemaForm.UnqualifiedElement要素の名前空間が に設定されるのはなぜですか?""XmlTypeAttribute

この種のコード (XmlSchemaForm.Unqualified部分) はWSCF.blueツールによって生成され、名前空間を台無しにしています。

4

1 に答える 1

0

要素の型で指定された名前空間をオーバーライドできます。例えば、あなたが持つことができます

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

Microsoft の の実装は、への設定とForm = XmlSchemaForm.Unqualifiedまったく同じように見えます。特に、他の名前空間を明示的に指定した場合は使用できません ( MSDN リファレンス)。その場合、次の例外が発生します。Namespace""

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 に答える