c# - XML Deserialize with same element name and different attributes​ name -


i want deseralize following xml in c#

<test> <testdata> <abc name = "fname"> test</abc> <abc name = "lname"> name</abc </testdata> </test> 

i have small example, have larger xml needs deseralize .net objects!! below object have

public class employee {       public string lastname {get; set;}       public string firstname {get;set;} } 

how deseralize such xml using either linq or xml serializer.

currently using xdocument, getting node name abc , using if else ladder constructing object not right way.

test first name name last name in xml..

any appreciated!!

the mapping describe not 1 supported xmlserializer. cannot serialize employee in way without 1 of:

  • implementing ixmlserializable - not recommend; easy make mess of this, particularly deserialization code
  • doing manually via xdocument or xmldocument (again, quite bit of work)
  • creating dto model usable xmlserializer matches schema

frankly, use last option, means creating (completely untested, i'll try in minute):

[xmlroot("test")] public class dtoroot {     [xmlarray("testdata")]     [xmlarrayitem("abc")]     public list<keyvaluepair> items {get;} = new list<keyvaluepair>();      public string this[string key] => items.firstordefault(x => x.key == key)?.value; } public class keyvaluepair{     [xmlattribute("name")]     public string key {get;set;}     [xmltext]     public string value {get;set;} } 

and use like:

employee emp = new employee {     firstname = "fred",     lastname = "flintstone" }; var obj = new dtoroot {     items = {     new keyvaluepair { key = "fname", value = emp.firstname },     new keyvaluepair { key = "lname", value = emp.lastname}, } }; var ser = new xmlserializer(typeof(dtoroot)); ser.serialize(console.out, obj); 

which gives (ignore encoding - because of console.out):

<?xml version="1.0" encoding="ibm850"?> <test xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"     xmlns:xsd="http://www.w3.org/2001/xmlschema">   <testdata>     <abc name="fname">fred</abc>     <abc name="lname">flintstone</abc>   </testdata> </test> 

to deserialize: deserialize dtoroot instance, use indexer:

var obj = (dtoroot)ser.deserialize(source); var emp = new employee {     firstname = obj["fname"],     lastname = obj["lname"], }; 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -