views:

245

answers:

2

I Have this XML File

<?xml version="1.0" standalone="yes"?>
<Root>
    <Object>
     <referenceName>People</referenceName>
     <query>select * from people</query>
    </Object>
    <Object>
     <referenceName>Countries</referenceName>
     <query>select * from countries</query>
    </Object>
</Root>

I need to convert into an object with C#.

I got confused how to do it. Kindly note that I can have alot of objects in the xml file.

I know that i have to use an [XMLArray......

Thanks

+2  A: 

Use the xsd.exe tool to generate an initial set of classes to start with. Once you have those, tweak if needed (post the generated classes) and use System.Xml.Serialization.XmlSerializer to deserialize back into the runtime object.

Wim Hollebrandse
+4  A: 

The simplest trick here is at the VS command line:

xsd example.xml
xsd example.xsd /classes

Et voila; one example.cs file with example C# that shows how to get that xml from .NET objects via XmlSerializer.

In this case, I expect the following would work:

public class Root
{
    [XmlElement("Object")]
    public List<SomeOtherObject> Objects { get; set; }
}

public class SomeOtherObject
{
    [XmlElement("referenceName")]
    public string Name { get; set; }
    [XmlElement("query")]
    public string Query { get; set; }
}

update: validated it; yup, it works...

XmlSerializer ser = new XmlSerializer(typeof(Root));
using (XmlReader reader = XmlReader.Create(
    new StringReader(xml)))
{
    var obj = (Root)ser.Deserialize(reader);
    // use obj
}
Marc Gravell
very nice 10q :)
David Bonnici