简体   繁体   中英

Deserialize xml which uses attribute name/value pairs

My application receives a constant stream of xml files which are more or less a direct copy of the database record

<record type="update">
    <field name="id">987654321</field>
    <field name="user_id">4321</field>
    <field name="updated">2011-11-24 13:43:23</field>
</record>

And I need to deserialize this into a class which provides nullable property's for all columns

class Record {
    public long? Id { get; set; }
    public long? UserId { get; set; }
    public DateTime? Updated { get; set; }
}

I just cant seem to work out a method of doing this without having to parse the xml file manually and switch on the field's name attribute to store the values. Is their a way this can be achieved quickly using an XmlSerializer? And if not is their a more efficient way of parsing it manually?

Regards and thanks


My main problem is that the attribute name needs to have its value set to a property name and its value as the contents of a <field>..</field> element

Edit Edited the answer to reflect the best you can get with your current xml layout you will get an array of field objects with two properties, Name, eg ID, and Value, the text in the node

You can create an Xml Definition class, pass this to an Xml Serializer and it will return you the object with the values of your xml intialised into it's properties.

So given the following definition file.

    [XmlTypeAttribute]
    [XmlRootAttribute("record")]
    public class RecordXmlConfiguration
    {

        [XmlElementAttribute("field")]
        public Field[] Fields { get; set; }


    }

    [XmlTypeAttribute]
    public class Field
    {
        [XmlAttributeAttribute("name")]
        public string Name { get; set; }

        [XmlText]
        public string Value { get; set; }
    }

Then when you have your xml you pass it to a method and it should return you an object of the type of your Xml defintiion class as so

    public static object Deserialize(string xml)
    {
        var deserializer = new System.Xml.Serialization.XmlSerializer(typeof(RecordXmlConfiguration));
        using (var reader = XmlReader.Create(new StringReader(xml)))
        {
            return (RecordXmlConfiguration)deserializer.Deserialize(reader);
        }
    }

It can be fiddly, but when its set up right it's saved me tonnes of time, as when your done with it you can also create a serialize method in the same maanner to return it to it's Xml form.

make sure to add references to your project to allow for these using statements

using System.Xml.Serialization;
using System.Xml;

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