[英]C# XML Deserialization into multiple objects
我正在將給定的XML文件反序列化為單個對象,我可以正常工作。 但是,現在我要對XML文件進行調整,以便我可以將額外的屬性反序列化為一個單獨的對象,以便從一個給定的xml文件可以填充兩個對象,這是否可以在一個操作中完成?
這是我當前的代碼和XML:
XML現在:
<NameCollection>
<Names>
<Name>
<description></description>
<Name>
<Name>
<description></description>
<Name>
</Names>
</NameCollection>
XML如我所願:
<NameCollection>
<GenericName></GenericName>
<GenericDescription></GenericDescription>
<Names>
<Name>
<description></description>
<Name>
<Name>
<description></description>
<Name>
</Names>
</NameCollection>
碼:
NameCollection commands;
XMLSerializer serializer = new XMLSerializer(typeof(NameCollection));
StreamReader streamReader = new StreamReader(xmlpath);
commands = (NameCollection)serializer.Derserialize(streamreader);
streamReader.Close();
和當前對象:
[Serializable()]
public class TestCommand
{
public string description{get;set;}
}
[Serializable()]
[XmlRoot("NameCollection")]
public class NameCollection
{
[XmlArray("Commands")]
[XmlArrayItem("Command", typeof(TestCommand))]
public TestCommand[] TestCommand {get;set;}
}
然后,我希望將GenericName和GenericDescription屬性添加到另一個單獨的對象,這就是我所堅持的。
我認為您要做的是讓您的類反映XML的結構,而不是兩個類。 所以你想要一個像這樣的結構:
public class TestCommand
{
public string description{get;set;}
}
[XmlRoot("NameCollection")]
public class NameCollection
{
public string GenericName {get; set;}
public string GenericDescription {get; set;}
[XmlArray("Commands")]
[XmlArrayItem("Command", typeof(TestCommand))]
public TestCommand[] TestCommand {get;set;}
}
然后以完全相同的方式序列化它,完成工作。
有了布局, XmlSerializer
唯一想要將這些額外的值放到NameCollection
上的NameCollection
,即
[XmlRoot("NameCollection")]
public class NameCollection
{
public string GenericName {get;set:}
public string GenericDescription {get;set:}
[XmlArray("Names")]
[XmlArrayItem("Name", typeof(TestCommand))]
public TestCommand[] TestCommand {get;set;}
}
如果希望它繼續作用於其他對象,則: XmlSerializer
不會這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.