简体   繁体   中英

XML Deserialization of attributes

I have a complicated XML structure with hierarchical Process, Stage, Step, Task as follows:

<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>

Basically , a Process is made of Stages . And Stages are made of Steps and Steps are made of Tasks. Each of these have some assigned Users and some attributes like Name , page , status .etc.

All of these have their own 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;
    }
}

Stage 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;
    }
}

Step 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;
    }
}

Task 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;
    }
}

And the User 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;
    }
}

I have written GenerateXML() methods for eahc step to get the final XML displayed above (when called from EFDP User).

My question is : Is there a way I can read the above XML into the respective classes and objects as shown ? I tried my hand at XML Serialization but could not figure out how to do this for the attributes? I could always try a brute force way of reading this into objects but that would be very lengthy.

If I could get any ideas on this or if I could get any suggestions to improve the above design to enable reading XML into objects easily that would be great.

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();
    }
}

You can use XmlSerializer to serialize a property of a class as an XML attribute by applying the [XmlAttribute] : attribute to the property:

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; }
}

For more information on controlling and customizing XML serialization of .Net classes, see here: Attributes That Control XML Serialization .

Having done that, you can now serialize your class to an XElement or an XML string using extension methods such as the following:

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);
    }
}

Then you can use the extension methods like so:

        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);

Or, to deserialize:

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

Update

In order to use XmlSerializer , all your classes must have a public (possibly default) parameterless constructor . Also, in your XML, some of your lists are one level deep while some are two levels deep. One-level-deep lists need to be decorated with the XmlElement attribute, like so:

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

You also have a few name inconsistencies. These can be fixed by specifying an element name or attribute name , for instance:

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

Thus the following set of classes seem to read in your sample XML successfully:

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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM