You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将XML中的不同节点反序列化为不同对象?

嘿,这个问题我熟!要处理混合了Page和Ghost节点的XML反序列化,用基类+XmlSerializer特性就能完美解决,不用绕弯路。下面给你一步步的实现方案:

步骤1:定义共同基类BasePage

把Page和Ghost共享的属性抽出来,避免重复代码:

public class BasePage
{
    [XmlAttribute("PrintedPagePosition")]
    public int PrintedPagePosition { get; set; }

    [XmlAttribute("PDFPagePosition")]
    public int PDFPagePosition { get; set; }

    [XmlAttribute("IsColor")]
    public bool IsColor { get; set; }
}
步骤2:定义Page和Ghost子类

各自处理独有的属性(Page没有额外属性,直接继承即可):

// Page子类:无额外属性,直接继承基类
public class Page : BasePage { }

// Ghost子类:添加独有的MayBePrinted属性
public class Ghost : BasePage
{
    [XmlAttribute("MayBePrinted")]
    public string MayBePrinted { get; set; }
}
步骤3:修改ColorPages类,配置序列化规则

通过[XmlElement]特性告诉XmlSerializer如何区分不同节点:

[XmlRoot("ColorPages")]
public class ColorPages
{
    public ColorPages()
    {
        Items = new List<BasePage>();
    }

    // 用两个XmlElement特性分别指定节点名称和对应子类
    [XmlElement("Page", Type = typeof(Page))]
    [XmlElement("Ghost", Type = typeof(Ghost))]
    public List<BasePage> Items { get; set; }
}
步骤4:反序列化并处理节点

现在可以正常反序列化XML,还能区分Page和Ghost类型:

var xmlContent = @"<?xml version=""1.0"" encoding=""utf-16""?>
<ColorPages version=""1"">
<Page PrintedPagePosition=""0"" PDFPagePosition=""0"" IsColor=""True"" />
<Ghost PrintedPagePosition=""1"" PDFPagePosition=""1"" MayBePrinted=""Unprinted"" IsColor=""False"" />
<Page PrintedPagePosition=""2"" PDFPagePosition=""2"" IsColor=""False"" />
<Ghost PrintedPagePosition=""3"" PDFPagePosition=""3"" MayBePrinted=""Unprinted"" IsColor=""False"" />
<Page PrintedPagePosition=""4"" PDFPagePosition=""4"" IsColor=""False"" />
<Page PrintedPagePosition=""5"" PDFPagePosition=""5"" IsColor=""True"" />
</ColorPages>";

var serializer = new XmlSerializer(typeof(ColorPages));
using var reader = new StringReader(xmlContent);
var colorPages = (ColorPages)serializer.Deserialize(reader);

// 遍历区分处理不同节点
foreach (var item in colorPages.Items)
{
    if (item is Page page)
    {
        Console.WriteLine($"常规页面 - PDF位置:{page.PDFPagePosition},是否彩色:{page.IsColor}");
    }
    else if (item is Ghost ghost)
    {
        Console.WriteLine($"Ghost页面 - PDF位置:{ghost.PDFPagePosition},打印状态:{ghost.MayBePrinted},是否彩色:{ghost.IsColor}");
    }
}

关键说明

核心是给Items属性添加两个[XmlElement]特性:分别指定XML中的节点名称(Page/Ghost)和对应的子类类型。XmlSerializer会自动根据节点标签实例化对应的对象,最终所有节点都会被统一放到List<BasePage>中,方便后续统一或区分处理。

内容的提问来源于stack exchange,提问作者Alexandru Pupsa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:03:06