XML 反序列化属性

XML Deserialization of attributes

我有一个复杂的 XML 结构,具有分层流程、阶段、步骤、任务,如下所示:

<Process>
    <Stage StageName="Data gathering" StagePage="page_DA.html" Status="Not Started" Selected="true">
        <StageUsers>
            <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
            <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
        </StageUsers>
        <Step StepName="Data acquistion - General" StepPage="page_DAGeneral.html" Status="Not Started">
            <StepUsers>
                <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
            </StepUsers>
            <Task TaskName="Well locations and reference elevations" TaskTip="Well locations and reference elevations" Status="Not Started">
                <TaskUsers>
                    <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                    <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
                </TaskUsers>
            </Task>
            <Task TaskName="Well deviation surveys" TaskTip="Well deviation surveys" Status="Not Started">
                <TaskUsers>
                    <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                    <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
                </TaskUsers>
            </Task>
        </Step>
        <Step StepName="Data acquistion - Petrophysics" StepPage="page_DAPetro.html" Status="Not Started">
            <StepUsers>
                <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
            </StepUsers>
            <Task TaskName="Digitization of maps and logs" TaskTip="Digitization of maps and logs" Status="Not Started">
                <TaskUsers>
                    <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                    <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
                </TaskUsers>
            </Task>
            <Task TaskName="Log data loading" TaskTip="Log data loading" Status="Not Started">
                <TaskUsers>
                    <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                    <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
                </TaskUsers>
            </Task>
            <Task TaskName="Special core analysis" TaskTip="Special core analysis" Status="Not Started">
                <TaskUsers>
                    <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                    <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
                </TaskUsers>
            </Task>
        </Step>
        <Step StepName="Data acquistion - Geology" StepPage="page_DAGeology.html" Status="Not Started">
            <StepUsers>
                <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
            </StepUsers>
            <Task TaskName="Stratigraphic correlations" TaskTip="Stratigraphic correlations" Status="Not Started">
                <TaskUsers>
                    <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                    <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
                </TaskUsers>
            </Task>
            <Task TaskName="Core data" TaskTip="Core data" Status="Not Started">
                <TaskUsers>
                    <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                    <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
                </TaskUsers>
            </Task>
            <Task TaskName="Geochemistry data" TaskTip="Geochemistry data" Status="Not Started">
                <TaskUsers>
                    <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                    <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
                </TaskUsers>
            </Task>
            <Task TaskName="Dip interpretation data" TaskTip="Dip interpretation data" Status="Not Started">
                <TaskUsers>
                    <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                    <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
                </TaskUsers>
            </Task>
            <Task TaskName="Existing digital time or depth structure maps" TaskTip="Existing digital time or depth structure maps" Status="Not Started">
                <TaskUsers>
                    <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                    <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
                </TaskUsers>
            </Task>
            <Task TaskName="Existing digital property maps" TaskTip="Existing digital property maps" Status="Not Started">
                <TaskUsers>
                    <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                    <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
                </TaskUsers>
            </Task>
        </Step>
        <Step StepName="Data acquistion - Geophysics" StepPage="page_DAGeophysics.html" Status="Not Started">
            <StepUsers>
                <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
            </StepUsers>
            <Task TaskName="Seismic data loading" TaskTip="Seismic data loading" Status="Not Started">
                <TaskUsers>
                    <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                    <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
                </TaskUsers>
            </Task>
            <Task TaskName="Stacking velocity ata loading" TaskTip="Stacking velocity ata loading" Status="Not Started">
                <TaskUsers>
                    <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                    <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
                </TaskUsers>
            </Task>
            <Task TaskName="VSP or check shot data" TaskTip="VSP or check shot data" Status="Not Started">
                <TaskUsers>
                    <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                    <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
                </TaskUsers>
            </Task>
        </Step>
        <Step StepName="Data acquistion - Engineering" StepPage="page_DAEng.html" Status="Not Started">
            <StepUsers>
                <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
            </StepUsers>
            <Task TaskName="Drilling and completion data" TaskTip="Drilling and completion data" Status="Not Started">
                <TaskUsers>
                    <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                    <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
                </TaskUsers>
            </Task>
            <Task TaskName="Pressure transient data" TaskTip="Pressure transient data" Status="Not Started">
                <TaskUsers>
                    <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                    <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
                </TaskUsers>
            </Task>
            <Task TaskName="Production data" TaskTip="Production data" Status="Not Started">
                <TaskUsers>
                    <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                    <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
                </TaskUsers>
            </Task>
            <Task TaskName="Pressure data" TaskTip="Pressure data" Status="Not Started">
                <TaskUsers>
                    <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                    <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
                </TaskUsers>
            </Task>
            <Task TaskName="Sample chracterization" TaskTip="Sample chracterization" Status="Not Started">
                <TaskUsers>
                    <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                    <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
                </TaskUsers>
            </Task>
        </Step>
        <Step StepName="Data acquistion - Additional" StepPage="page_DAAdd.html" Status="Not Started">
            <StepUsers>
                <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
            </StepUsers>
            <Task TaskName="New cores" TaskTip="New cores" Status="Not Started">
                <TaskUsers>
                    <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                    <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
                </TaskUsers>
            </Task>
            <Task TaskName="Special core analysis for Geomechanics" TaskTip="Special core analysis for Geomechanics" Status="Not Started">
                <TaskUsers>
                    <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                    <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
                </TaskUsers>
            </Task>
            <Task TaskName="Core sampling" TaskTip="Core sampling" Status="Not Started">
                <TaskUsers>
                    <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                    <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
                </TaskUsers>
            </Task>
            <Task TaskName="Laboratory tests" TaskTip="Laboratory tests" Status="Not Started">
                <TaskUsers>
                    <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
                    <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
                </TaskUsers>
            </Task>
        </Step>
    </Stage>
    <Stage StageName="Well reservoir production review" StagePage="page_WRPR.html" Status="Not Started" Selected="true">
        <StageUsers>
            <User Alias="PNeelakandan" FullName="Prasaanth Neelakandan" Role="Dev" Email="PNeelakandan@exchange.com" Organization="Windows"/>
            <User Alias="SGuo3" FullName="Wen Jiao" Role="Dev" Email="SGuo3@exchange.com" Organization="Windows"/>
        </StageUsers>
    </Stage>
</Process>

基本上,流程由阶段组成。阶段由步骤组成,步骤由任务组成。其中每一个都有一些分配的用户和一些属性,如 Name 、 page 、 status 等。

所有这些都有自己的 classes :

public class Process
{
    public string ProcessName { get; set; }
    public string HelpFile { get; set; }
    public List<Stage> Stages { get; set; }
    public Process()
    {
        Stages = new List<Stage>();
    }

    public XElement GenerateXML()
    {
        var proc = new XElement("Process");

        foreach (Stage stg in Stages)
        {
            proc.Add(stg.GenerateXML());
        }

        // this returns the final Process XML
        return proc;
    }
}

阶段Class:

public class Stage
{
    public string StageName { get; set; }
    public string stagepage { get; set; }
    public List<Step> Steps { get; set; }
    public List<User> StageUsers { get; set; }
    public string StageStatus { get; set; }

    public bool IsSelected;

    public Stage(String name)
    {
        StageName = name;
        Steps = new List<Step>();
        StageUsers = new List<User>();
        Selected = true;
    }
    public XElement GenerateXML()
    {
        var proj = new XElement("Stage",
            new XAttribute("StageName", StageName),
            new XAttribute("StagePage", stagepage),
            new XAttribute("Status", StageStatus), 
            new XAttribute("Selected", IsSelected)
            );
        var users = new XElement("StageUsers");
        foreach (User stgUser in StageUsers)
        {
            users.Add(stgUser.GenerateXML());
        }
        proj.Add(users);

        foreach (Step st in Steps)
        {
            proj.Add(st.GenerateXML());
        }
        return proj;
    }
}

步骤Class:

public class Step
{
    public string StepName { get; set; }
    public string StepPage { get; set; }
    public List<Task> Tasks { get; set; }
    public List<User> StepUsers { get; set; }
    public string StepStatus { get; set; }

    public Step(String name)
    {
        StepName = name;
        Tasks = new List<Task>();
        StepUsers=new List<User>();
    }

    public XElement GenerateXML()
    {
        var proj = new XElement("Step",
            new XAttribute("StepName", StepName),
            new XAttribute("StepPage", StepPage),
            new XAttribute("Status", StepStatus)
            );
        var users = new XElement("StepUsers");
        foreach (User stpUser in StepUsers)
        {
            users.Add(stpUser.GenerateXML());
        }
        proj.Add(users);

        foreach (Task tk in Tasks)
        {
            proj.Add(tk.GenerateXML());
        }
        return proj;
    }
}

任务Class:

public class Task
{
    public string TaskTip { get; set; }
    public string TaskName { get; set; }
    public List<User> TaskUsers { get; set; }
    public string TaskStatus { get; set; }
    public Task(String name)
    {
        TaskName = name;
        TaskUsers = new List<User>();
    }

    public XElement GenerateXML()
    {
        var proj = new XElement("Task",
            new XAttribute("TaskName", TaskName),
            new XAttribute("TaskTip", TaskTip)
           ,
            new XAttribute("Status", TaskStatus)
            );

        var users = new XElement("TaskUsers");
        foreach (User tkUser in TaskUsers)
        {
            users.Add(tkUser.GenerateXML());
        }
        proj.Add(users);
        return proj;
    }
}

用户 class :

public class User
{
    public string Alias { get; set; }
    public string FullName { get; set; }
    public string Email { get; set; }
    public string Role { get; set; }
    public string Organization { get; set; }

    public XElement GenerateXML()
    {
        var proj = new XElement("User",
          new XAttribute("Alias", Alias),
          new XAttribute("FullName", FullName),
          new XAttribute("Role", Role),
          new XAttribute("Email", Email),
          new XAttribute("Organization", Organization)
          );

        return proj;
    }
}

我已经为 eahc 步骤编写了 GenerateXML() 方法以获得上面显示的最终 XML(当从 EFDP 用户调用时)。

我的问题是:有没有一种方法可以将上面的 XML 读入相应的 classes 和对象,如图所示?我尝试了 XML 序列化,但不知道如何为属性执行此操作? 我总是可以尝试用蛮力的方式将其读入对象,但这会非常冗长。

如果我能对此有任何想法,或者如果我能得到任何改进上述设计的建议,以便能够轻松地将 XML 读取到对象中,那就太好了。

public class Reviewer
{
    [XmlAttribute]
    public string Verdict { get; set; }

    [XmlAttribute]
    public string Comments { get; set; }

    [XmlElement]
    public User User { get; set; }

    public Reviewer()
    {
        User = new User();
    }
}

您可以使用 XmlSerializer to serialize a property of a class as an XML attribute by applying the [XmlAttribute]: 属性到 属性:

public class User
{
    [XmlAttribute]
    public string Alias { get; set; }
    [XmlAttribute]
    public string FullName { get; set; }
    [XmlAttribute]
    public string Email { get; set; }
    [XmlAttribute]
    public string Role { get; set; }
    [XmlAttribute]
    public string Organization { get; set; }
}

有关控制和自定义 XML .Net classes 序列化的更多信息,请参阅此处:Attributes That Control XML Serialization.

完成后,您现在可以使用如下扩展方法将 class 序列化为 XElement 或 XML 字符串:

public static class XmlSerializationExtensions
{
    public static string ToXml<T>(this T obj)
    {
        return obj.ToXml(false);
    }

    public static string ToXml<T>(this T obj, bool omitStandardNamespaces)
    {
        using (var textWriter = new StringWriter())
        {
            var settings = new XmlWriterSettings() { Indent = true, IndentChars = "  " }; // For cosmetic purposes.
            using (var writer = XmlWriter.Create(textWriter, settings))
            {
                XmlSerializerNamespaces ns = null;
                if (omitStandardNamespaces)
                    (ns = new XmlSerializerNamespaces()).Add("", ""); // Disable the xmlns:xsi and xmlns:xsd lines.
                new XmlSerializer(obj.GetType()).Serialize(writer, obj, ns);
            }
            return textWriter.ToString();
        }
    }

    public static T DeserializeXML<T>(this string xmlString)
    {
        using (var reader = new StringReader(xmlString))
        {
            var result = new XmlSerializer(typeof(T)).Deserialize(reader);
            if (result is T)
                return (T)result;
        }
        return default(T);
    }

    public static XElement ToXElement<T>(this T obj)
    {
        return obj.ToXElement(true);
    }

    public static XElement ToXElement<T>(this T obj, bool omitStandardNamespaces)
    {
        var doc = new XDocument();
        using (var writer = doc.CreateWriter())
        {
            XmlSerializerNamespaces ns = null;
            if (omitStandardNamespaces)
                (ns = new XmlSerializerNamespaces()).Add("", ""); // Disable the xmlns:xsi and xmlns:xsd lines.
            new XmlSerializer(obj.GetType()).Serialize(writer, obj, ns);
        }
        var element = doc.Root;
        if (element != null)
            element.Remove();
        return element;
    }

    public static T DeserializeXML<T>(this XContainer element)
    {
        using (var reader = element.CreateReader())
        {
            var result = new XmlSerializer(typeof(T)).Deserialize(reader);
            if (result is T)
                return (T)result;
        }
        return default(T);
    }
}

然后你可以像这样使用扩展方法:

        var user = new User { Alias = "foo", Email = "bar@none.net", FullName = "full name name", Organization = "disorganized", Role = "forward" };
        var xml = user.ToXml();
        Debug.WriteLine(xml);
        var xElement = user.ToXElement();
        Debug.WriteLine(xElement);

或者反序列化:

        var process1 = xmlString.DeserializeXML<Process>();
        var process2 = xmlElement.DeserializeXML<Process>();

更新

为了使用 XmlSerializer,您所有的 classes 必须有一个 public(可能是默认的)parameterless constructor。此外,在您的 XML 中,有些列表是一层深的,有些是两层深的。一级深度列表需要用 XmlElement 属性修饰,如下所示:

    [XmlElement("Stage")]
    public List<Stage> Stages { get; set; }

您还有一些名字不一致的地方。这些可以通过指定 element name or attribute name 来修复,例如:

    [XmlAttribute("Selected")]
    public bool IsSelected { get; set; }

因此,以下一组 classes 似乎在您的示例中 XML 成功读取:

public class Process
{
    public string ProcessName { get; set; }
    public string HelpFile { get; set; }
    [XmlElement("Stage")]
    public List<Stage> Stages { get; set; }
    public Process()
    {
        Stages = new List<Stage>();
    }
}

public class Stage
{
    [XmlAttribute]
    public string StageName { get; set; }
    [XmlAttribute("StagePage")]
    public string stagepage { get; set; }
    [XmlAttribute("Status")]
    public string StageStatus { get; set; }
    [XmlAttribute("Selected")]
    public bool IsSelected { get; set; }

    [XmlElement("Step")]
    public List<Step> Steps { get; set; }
    public List<User> StageUsers { get; set; }

    public Stage() : this(null) { }

    public Stage(String name)
    {
        StageName = name;
        Steps = new List<Step>();
        StageUsers = new List<User>();
        IsSelected = true;
    }
}

public class Step
{
    [XmlAttribute]
    public string StepName { get; set; }
    [XmlAttribute]
    public string StepPage { get; set; }
    [XmlAttribute("Status")]
    public string StepStatus { get; set; }

    [XmlElement("Task")]
    public List<Task> Tasks { get; set; }
    public List<User> StepUsers { get; set; }

    public Step() : this(null) { }

    public Step(String name)
    {
        StepName = name;
        Tasks = new List<Task>();
        StepUsers = new List<User>();
    }
}

public class Task
{
    [XmlAttribute]
    public string TaskName { get; set; }
    [XmlAttribute]
    public string TaskTip { get; set; }
    [XmlAttribute("Status")]
    public string TaskStatus { get; set; }

    public List<User> TaskUsers { get; set; }

    public Task() : this(null) { }

    public Task(String name)
    {
        TaskName = name;
        TaskUsers = new List<User>();
    }
}

public class User
{
    [XmlAttribute]
    public string Alias { get; set; }
    [XmlAttribute]
    public string FullName { get; set; }
    [XmlAttribute]
    public string Email { get; set; }
    [XmlAttribute]
    public string Role { get; set; }
    [XmlAttribute]
    public string Organization { get; set; }
}