0

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.

2
  • Use XmlSerializer Class Commented Sep 30, 2016 at 18:14
  • Thanks for hint. Please check my edit to see what I already have tried. Commented Sep 30, 2016 at 18:20

1 Answer 1

2

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic! Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.