FLICKER FLICKER - 2 months ago 18
C# Question

Generate list of objects from XML stored in SqlXml variable

I have

BIObject
class

public class BIObject
{
public string Database { get; set; }
public string Schema { get; set; }
public string Name { get; set; }
public string ObjectType { get; set; }
}


and also have below XML

<root>
<objects>
<object database="LynxReporting" schema="dbo" name="rptusp_GLTDRSummary" type="P"/>
<object database="IntraDay" schema="dbo" name="BMHGLCloseDetails" type="T"/>
<object database="LynxReporting" schema="dbo" name="factGeneralLedger" type="P"/>
</objects>
</root>


I need to create
List<IBObject>
from the XML

Note: I load the XML from database into a property of type SqlXml so I need to convert SqlXml to
List<IBObject>


Looked at couple of answers but could not figure out how I can do that.

EDIT:

I used below code

using (StringReader reader = new StringReader(myXmlString))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<BIObject>));
List<BIObject> objs = (List<BIObject>)serializer.Deserialize(reader);
}


but got error


There is an error in XML document (1, 2).


and


root xmlns='' was not expected.

Answer

Create a class which "represent" your xml structure

[XmlRoot("root")]
public class BIObjects
{
    public BIObjects() 
    {
        Objects = new List<BIObject>();
    }

    [XmlArray("objects")]
    [XmlArrayItem("object")]
    public List<BIObject> Objects { get; set; }
}

public class BIObject
{
    [XmlAttribute("database")]
    public string Database { get; set; }

    [XmlAttribute("schema")]
    public string Schema { get; set; }

    [XmlAttribute("name")]
    public string Name { get; set; }

    [XmlAttribute("type")]
    public string ObjectType { get; set; }
}

Then use same serializer code you provide in the question

using (StringReader reader = new StringReader(myXmlString))
{
    XmlSerializer serializer = new XmlSerializer(typeof(BIObjects));
    var objs = (BIObjects)serializer.Deserialize(reader);

    // use results
    // foreach(BIObject obj in objs.Objects)
}
Comments