Derek
Derek

Reputation: 8630

Xml De-Serialisation No Root Node

I have an XML file that I'm receiving form a third party provider.

It's not structured in the conventional way, it basically has no Root :-

<DG_X
    attrib1="Test2"
    attrib2="1"
    attrib3="12345">TEST-23456</DG_X>
<DG_Y
    attrib1="test"
    attrib2="Example Text"
    attrib3="1"
    attrib4="3"
    attrib5= 1
    attrib6="12412342134">Test-1234567</DG_Y>

I'm only interested in the first Element "DG_X" and i only need its value "TEST-23456".

I'm new to De-Serialistaion, and so far my attempts have failed :-

[Serializable]
    [XmlRoot("DG_X")]
    public class DM
    {
        [XmlText]
        public string Value { get; set; }

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

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

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

        [XmlIgnore]
        [XmlElement("DG_Y")]
        public string dg_key { get; set; }

    }

The problem lies with reading the second Element, The compiler advises that there are two root elements. What is the best way to tackle this issue?

Upvotes: 0

Views: 262

Answers (2)

Derek
Derek

Reputation: 8630

I managed to get round my problem with the following code:-

This was the only way I could get round having no root node in the file.

using (var fileSteam = new StreamReader(fileStream))
            {
                var settings = new XmlReaderSettings {ConformanceLevel = ConformanceLevel.Fragment};

                using (var reader = XmlReader.Create(fileSteam, settings))
                {
                    if (!reader.IsStartElement()) 
                        return String.Empty;

                    var reference = reader.ReadElementContentAsString();
                    return reference.StartsWith("DM-") ? reference : string.Format("DM-{0}", reference);
                }

Upvotes: 0

Marvin Smit
Marvin Smit

Reputation: 4108

The following should work for your example


 XmlReader xR = XmlReader.Create(@"example.xml");
            xR.MoveToContent();

            XmlSerializer xser = new XmlSerializer(typeof(DM));
            DM dmInstance = xser.Deserialize(xR) as DM;

We're basically using an XmlReader to position ourselfs on the first element and using that to deserialize into the object instance.

Hope this helps,

Upvotes: 1

Related Questions