我有一个描述网站的 XML 文件。它由站点作为根节点组成,可以有页面,页面可以有按钮或文本框和对话框等对象。对话框也可以有对象。
在相应的C#类中,全部派生自Element。当我反序列化 XML 时,如何才能引用正在构造的元素的父级?
我被告知复杂类型不能以这种方式反序列化,但如果我向 XML 中的每个元素添加 ID 字段,则可以使用它引用父级,从而正确反序列化。我将如何实施?我不想手动向 XML 文件中的每个元素添加 ID 字段...
我的元素类:
public class Element
{
public string Name { get; set; }
public string TagName { get; set; }
public string XPath { get; set; }
[XmlElement(ElementName = "Site", Type = typeof(Site))]
[XmlElement(ElementName = "Page", Type = typeof(Page))]
[XmlElement(ElementName = "Dialog", Type = typeof(Dialog))]
public Element Parent { get; set; }
[XmlArray("Children", IsNullable = false)]
[XmlArrayItem(Type = typeof(TextBox))]
[XmlArrayItem(Type = typeof(Page))]
[XmlArrayItem(Type = typeof(Button))]
[XmlArrayItem(Type = typeof(Dialog))]
public Collection<Element> Children { get; set; }
}
我的反序列化:
public Site GetSiteFromXml(string filePath, string fileName)
{
XmlSerializer serializer = new XmlSerializer(typeof(Site));
return serializer.Deserialize(new XmlTextReader(Path.Combine(filePath, fileName))) as Site;
}
我的 XML 文件:
<Site>
<Name>WebSiteName</Name>
<Url>https://site.url</Url>
<Children>
<Page>
<Name>HomePage</Name>
<Address>#page=1</Address>
<Children>
<Button>
<Name>LoginDialogButton</Name>
<Id>LoginIcon</Id>
<XPath>//*[@id="LoginIcon"]</XPath>
<Enabled>true</Enabled>
<Action>OpenLoginDialog</Action>
</Button>
<Dialog>
<Name>LoginPopUpDialog</Name>
<Id>loginModal</Id>
<Children>
<TextBox>
<Name>UserNameInput</Name>
</TextBox>
<TextBox>
<Name>PasswordInput</Name>
</TextBox>
<Button>
<Name>LoginButton</Name>
<Action>DialogDismiss</Action>
</Button>
</Children>
</Dialog>
</Children>
</Page>
</Children>
</Site>