Tuesday, 15 April 2014

c# - Cannot parse simple XML into an object? -



c# - Cannot parse simple XML into an object? -

i getting frustrated

xml

<meterwalkorder> <name>red route</name> <meters> <meter> <meterid>1</meterid> <serialnumber>12345</serialnumber> </meter> <meter> <meterid>2</meterid> <serialnumber>se</serialnumber> </meter> </meters> </meterwalkorder>

i cannot simple xml object using serializer

var xml = file.readalltext("walkorder.xml"); var xmlserializer = new nformats.xml.xmlserializer(); var obj = xmlserializer.deserialize<meterwalkorder>(new stringreader(xml));

please can help urgently wasting me hours!!

i 2 meter objects have none of attributes set , name not set in walk order. dont understand how simple can complicated lol

public partial class meterwalkorder { public meterwalkorder() { meters = new list<meter>(); } [datamember] public string name { get; set; } } } using system; using system.xml.serialization; namespace windowsformsapplication1.classes { public class meter : imeter { [xmlattribute] public int meterid { get; set; } [xmlattribute] public string serialnumber { get; set; } } }

i willing seek xml serializer need works!!

paul

first of suggest read introducing xml serialization on msdn made couple of errors lead not mentioned exceptions thrown when run code.

in xml meterid , serialnumber not attributes elements. (as wyat earp commented) if want serialize have tell should [serializable] serialization requires implemented public empty constructor dont open streams when not closing them (use "using") to test if serialization works best first serialize, check output , implement deserialize

find working illustration below:

using system; using system.collections.generic; using system.io; using system.xml; using system.xml.serialization; namespace x123 { static class programme { /// <summary> /// main entry point application. /// </summary> [stathread] static void main() { meterwalkorder mo = new meterwalkorder(); mo.name = "name"; mo.meters.add(new meter { meterid = 1, serialnumber = "kdkdkd" }); mo.meters.add(new meter { meterid = 2, serialnumber = "holladrio" }); var xmlserializer = new xmlserializer(typeof(meterwalkorder), new type[] { typeof(meter) }); { xmlserializer.serialize(file.createtext("hello.xml"), mo); using (stream s = file.openread("hello.xml")) { var obj = xmlserializer.deserialize(s); } } } } [serializable] public class meterwalkorder { public meterwalkorder() { } public string name { get; set; } public list<meter> meters { { homecoming meters; } set { meters = value; } } private list<meter> meters = new list<meter>(); } [serializable] public class meter { public meter() { } [xmlattribute] public int meterid { get; set; } [xmlattribute] public string serialnumber { get; set; } }

c# xml xml-serialization xml-deserialization

No comments:

Post a Comment