2012-01-24 8 views
0

ネストされたオブジェクトを直列化して、そのプロパティが親オブジェクトと同じレベルになるようにしたい(つまり、ネストされたタグではない)。具体的に:私はC#のオブジェクトがあります。ネストされたオブジェクトのXMLシリアル化がルートレベルで

[XmlRoot(ElementName="Root")] 
public class TopLevel 
{ 
    public string topLevelProperty; 
    public NestedObject nestedObj; 
} 

public class NestedObject 
{ 
    string propetyOnNestedObject; 
} 

をし、私が望むようなXML:

<root> 
    <topLevelProperty>...</topLevelProperty> 
    <propertyOnNestedObject>...</propertyOnNestedObject> 
    <!--NOTE: propertyOnNestedObject would normally be inside a "<nested>" tag 
     but I'm trying to avoid that here--> 
</root> 

があることは可能ですか?

答えて

1

あなたは正しくインターフェイスを実装する方法についてCodeProjectので良いポストもあり、デフォルトの動作

[XmlRoot(ElementName = "Root")] 
public class TopLevel : IXmlSerializable 
{ 
    public string topLevelProperty; 
    public NestedObject nestedObj; 

    public XmlSchema GetSchema() 
    { 
     return null; 
    } 

    public void ReadXml(XmlReader reader) 
    { 
     //... 
    } 

    public void WriteXml(XmlWriter writer) 
    { 
     writer.WriteElementString("topLevelProperty", topLevelProperty); 
     writer.WriteElementString("propertyOnNestedObject", nestedObj.propetyOnNestedObject); 
    } 
} 

を上書きするIXmlSerializableインタフェースを実装する必要があります。http://www.codeproject.com/Articles/43237/How-to-Implement-IXmlSerializable-Correctly

1

はあなたが公開することができますケースとしてネストされたproeprtyアクセサですが、これはTopLevelオブジェクトをわずかに複雑にします。したがって、そのような特殊ケースのラッパーをビジネス・オブジェクト自体から切り離すために、別個のシリアライズ可能ラッパーを導入することができます。

[XmlRoot(ElementName="Root")] 
public class TopLevel 
{  
    public string topLevelProperty;  

    [XmlIgnore] 
    public NestedObject nestedObj; 

    [XmlElement("NestedProperty")] 
    public string NestedPropertyAccessor 
    { 
     get 
     { 
     return nestedObj.NestedProperty; 
     } 
     // set 
    } 
} 

ORあなたはあなただけのシリアル化形式に合わせて特別に公開されたプロパティによって、ビジネスオブジェクト自体を複雑にする必要はありませんので、ビジネスモデルから直列化可能なオブジェクトを切り離す必要がある場合は、それを区切ります

public class TopLevelSerializableWrapper 
{ 
    public TopLevelSerializableWrapper(TopLevel businessObject) 
    { 
    } 

    // TODO: expose all proeprties which need to serialized 
} 
0

あなたがしてこれを行うことができます簡単YAXLib XMLシリアル化ライブラリ:

//[XmlRoot(ElementName = "Root")] 
[YAXSerializeAs("Root")] 
public class TopLevel 
{ 
    public string topLevelProperty { get; set; } 
    public NestedObject nestedObj { get; set; } 
} 

public class NestedObject 
{ 
    [YAXElementFor("..")] 
    string propetyOnNestedObject { get; set; } 
} 

YAXElementFor("..")属性はSERIALIZの場所を指示する方法注親要素へのアクセス。 (".."は、ファイルシステムパスで親フォルダが好きに見えます)。

関連する問題