xsd.exe のスキーマから生成されたクラスを使用して、C# で xml ファイルを逆シリアル化しようとしています。残念ながら、ファイルの一部のみが適切に逆シリアル化されています。残りは、解決できない理由で null として返されます。
私のプロセスは次のとおりです。C# コードが生成される myschema.xsd ファイルから始めます。
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:mc="myschema:common" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ttl="http://www.myuri.org/myschema" targetNamespace="http://www.myuri.org/myschema" elementFormDefault="qualified" attributeFormDefault="unqualified">
インポートされたparentschema.xsdファイルは次のとおりです。
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:mc="myschema:common" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="myschema:common" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:element name="toplevel">
<xs:complexType>
<xs:sequence>
<xs:element ref="mc:toplevel_header" minOccurs="0"/>
<xs:element ref="mc:body"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="toplevel_header">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:anyURI"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="body" type="mc:body" abstract="true"/>
<xs:complexType name="body">
<xs:attribute name="id" type="xs:ID" use="required"/>
</xs:complexType>
<xs:element name="Entity" type="mc:Entity" abstract="true"/>
<xs:complexType name="Entity" abstract="true">
<xs:attribute name="href" type="xs:anyURI" use="optional"/>
</xs:complexType>
</xs:schema>
上記の 2 つのスキーマ ファイルを xsd.exe に渡します。
>xsd.exe /c myschema.xsd parentschema.xsd
myschema_parentschema.cs ファイルを生成します
それをテストするために、サンプルの xml ファイルを逆シリアル化しようとしています。
<?xml version=\"1.0\" encoding="UTF-8"?>
<toplevel version="2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns="myschema:common"
xsi:schemaLocation="myschema:common http://www.myuri.org/parentschema.xsd">
<toplevel_header>
<name>MyName</name>
</toplevel_header>
<body id="body_1"
xmlns="http://www.myuri.org/schema"
xmlns:mc="myschema:common"
xsi:schemaLocation="http://www.myuri.org/myschema http://www.myuri.org/myschema.xsd">
<Foo href="http://www.google.com">
</Foo>
</body>
</toplevel>
これを次の XmlSerializer コードに渡します。ここで、リーダーは上記の xml ファイルの XmlReader です。
XmlSerializer xs = new XmlSerializer ( typeof ( toplevel ) );
object deserializedObject = xs.Deserialize( reader );
toplevel fooBar = (toplevel)deserializedObject;
Assert.AreEqual( "MyName", fooBar.toplevel_header.name ); //passes OK
Assert.IsNotNull( fooBar.body ); //<--------FAIL
逆シリアル化されたオブジェクトに null body プロパティがあるのはなぜですか? また、Foo 要素を適切に逆シリアル化するにはどうすればよいですか?