2013-07-30 79 views
4

我正在使用XmlSerializer執行Xml序列化。我正在執行ClassA的序列化,其中包含ClassB類型的名爲MyProperty的屬性。我不希望ClassB的特定屬性被序列化。我不得不使用XmlAttributeOverrides作爲類在另一個庫中。 如果該物業本身是ClassA,那本來就很簡單。忽略Xml中屬性的屬性使用XmlSerializer在.NET中進行序列化

XmlAttributeOverrides xmlOver = new XmlAttributeOverrides(); 
XmlAttributes xmlAttr = new XmlAttributes(); 
xmlAttr.XmlIgnore = true; 
xmlOver.Add(typeof(ClassA), "MyProperty", xmlAttr); 

XmlSerializer ser = new XmlSerializer(typeof(ClassA), xmlOver); 

如何完成,如果該屬性是ClassB,我們需要序列ClassA

+0

我想你不想總是忽略其他案件在'ClassB'的財產?否則就像使用'[XmlIgnore]'裝飾'ClassBy.PropertyToIgnore'一樣簡單? –

+0

是@ChrisSinclair,你是對的。 – Brij

回答

4

你幾乎得到了它,只需更新您的覆蓋指向ClassB而不是ClassA

XmlAttributeOverrides xmlOver = new XmlAttributeOverrides(); 
XmlAttributes xmlAttr = new XmlAttributes(); 
xmlAttr.XmlIgnore = true; 

//change this to point to ClassB's property to ignore 
xmlOver.Add(typeof(ClassB), "ThePropertyNameToIgnore", xmlAttr); 

XmlSerializer ser = new XmlSerializer(typeof(ClassA), xmlOver); 

快速測試,給出:

public class ClassA 
{ 
    public ClassB MyProperty { get; set; } 
} 

public class ClassB 
{ 
    public string ThePropertyNameToIgnore { get; set; } 
    public string Prop2 { get; set; } 
} 

和導出方法:

public static string ToXml(object obj) 
{ 
    XmlAttributeOverrides xmlOver = new XmlAttributeOverrides(); 
    XmlAttributes xmlAttr = new XmlAttributes(); 
    xmlAttr.XmlIgnore = true; 
    xmlOver.Add(typeof(ClassB), "ThePropertyNameToIgnore", xmlAttr); 


    XmlSerializer xs = new XmlSerializer(typeof(ClassA), xmlOver); 
    using (MemoryStream stream = new MemoryStream()) 
    { 
     xs.Serialize(stream, obj); 
     return System.Text.Encoding.UTF8.GetString(stream.ToArray()); 
    } 
} 

主要方法:

void Main() 
{ 
    var classA = new ClassA { 
     MyProperty = new ClassB { 
      ThePropertyNameToIgnore = "Hello", 
      Prop2 = "World!" 
     } 
    }; 

    Console.WriteLine(ToXml(classA)); 
} 

輸出這個與「ThePropertyNameToIgnore」省略:

<?xml version="1.0"?> 
<ClassA xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <MyProperty> 
    <Prop2>World!</Prop2> 
    </MyProperty> 
</ClassA> 
相關問題