我試圖使用XmlAttributeOverrides來控制在類被序列化之後哪些類屬性出現在xml中。它適用於「根」類而不是嵌套屬性的屬性。這裏有一個簡單的例子來說明我正在努力完成什麼。在嵌套屬性上使用XmlAttributeOverrides
我的類層次結構如下所示:
public class Main
{
public string Name { get; set; }
public Location Address { get; set; }
}
public class Location
{
public string StreetAddress { get; set; }
public Contact ContactInfo{ get; set; }
}
public class Contact
{
public string PhoneNumber { get; set; }
public string EmailAddr { get; set; }
}
當我序列化的Main(),我得到的是這樣的:
<Main>
<Name></Name>
<Address>
<StreetAddress></StreetAddress>
<ContactInfo>
<PhoneNumber></PhoneNumber>
<EmailAddr></EmailAddr>
</ContactInfo>
</Address>
</Main>
我所能夠做的就是保持名稱或地址從出現使用此:
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
XmlAttributes attribs = new XmlAttributes();
attribs.XmlIgnore = true;
attribs.XmlElements.Add(new XmlElementAttribute("Address"));
overrides.Add(typeof(Main), "Address", attribs);
xs = new XmlSerializer(typeof(Main), overrides);
我還需要做的是保持Main.Address.ContactInf o被序列化有時候(如果它是空的)。我嘗試以下,但他們沒有工作:
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
XmlAttributes attribs = new XmlAttributes();
attribs.XmlIgnore = true;
attribs.XmlElements.Add(new XmlElementAttribute("ContactInfo "));
overrides.Add(typeof(Contact), "ContactInfo ", attribs);
xs = new XmlSerializer(typeof(Contact), overrides);
和...
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
XmlAttributes attribs = new XmlAttributes();
attribs.XmlIgnore = true;
attribs.XmlElements.Add(new XmlElementAttribute("ContactInfo "));
overrides.Add(typeof(Main.Address.ContactInfo), "ContactInfo ", attribs);
xs = new XmlSerializer(typeof(Main.Address.ContactInfo), overrides);
其實我已經嘗試了很多,使用XPath語句指定屬性名的目標,包括但不想填寫失敗的嘗試。我用這種方法甚至有可能問什麼?
很完美!非常感謝您爲此付出的努力! – user1437872 2013-05-13 18:11:04
@ user1437872:很高興您發現此答案有幫助。如果這能解決您的問題,您能否將這個答案標記爲答案?通過將此問題標記爲答案,它可以提高我在網站上的聲譽。這有助於他人知道網站上的信息可能有多好(或不是)。再次感謝您的積極評價! – fourpastmidnight 2013-05-13 18:18:06
感謝您的回答! – fourpastmidnight 2013-05-16 19:08:53