xml 示例:
<Profile>
<ProfileSections>
<ProfileSection Name="Default">
<Email>[email protected]</Email>
<Pasword>test</Pasword>
</ProfileSection>
<ProfileSection Name="Address">
<Street>Undermissed</Street>
</ProfileSection>
</ProfileSections>
</Profile>
如何反序列化此 XML 以使 List ProfileSections 和每個組態檔部分成為必要的物件?物件示例:
public class DefaultProdileSection{
[XmlAttribute]
public string Name{ get; set; }
public string Email{ get; set; }
public string PAssword{ get; set; }
}
public class AddressProdileSection{
[XmlAttribute]
public string Name{ get; set; }
public string Street{ get; set; }
}
uj5u.com熱心網友回復:
我們可以在決議的時候手動給xml令牌流添加一個type屬性。
如果你真的很想使用反序列化,那么我可以建議以下代碼。
類集:
public class Profile
{
public List<ProfileSection> ProfileSections { get; set; }
}
[XmlInclude(typeof(DefaultProfileSection))]
[XmlInclude(typeof(AddressProfileSection))]
public class ProfileSection
{
[XmlAttribute]
public string Name { get; set; }
}
public class DefaultProfileSection : ProfileSection
{
public string Email { get; set; }
public string Password { get; set; }
}
public class AddressProfileSection : ProfileSection
{
public string Street { get; set; }
}
一個自定義的 xml 閱讀器,它將即時添加必要的資訊:
public class TypeAddingXmlReader : XmlTextReader
{
public TypeAddingXmlReader(string url) : base(url) { }
// Define the remaining constructors here
public override string? GetAttribute(string localName, string? namespaceURI)
{
if (base.LocalName == "ProfileSection" &&
localName == "type" &&
namespaceURI == "http://www.w3.org/2001/XMLSchema-instance")
{
var name = base.GetAttribute("Name");
return name switch
{
"Default" => nameof(DefaultProfileSection),
"Address" => nameof(AddressProfileSection)
// add other class names here
};
}
return base.GetAttribute(localName, namespaceURI);
}
}
采用:
var ser = new XmlSerializer(typeof(Profile));
using var reader = new TypeAddingXmlReader("test.xml");
var profile = (Profile)ser.Deserialize(reader);
foreach (var ps in profile.ProfileSections)
Console.WriteLine(ps.Name " " ps.GetType());
命名空間:
using System.Xml;
using System.Xml.Serialization;
注意:但我會使用 linq to xml 而不會出汗。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/466248.html
上一篇:xslt在元素后添加處理指令
