Reputation: 8671
I have an object which I have created from an XML document using visual studio's xsd.exe
. Is there a way to populate an instance of this object with the contents of an XML document without having to manually set each property/attribute?
For example:
XElement doc = XElement.Parse(docStr);
var results = from e in doc.Elements("myobj")
select new MyObj { prop1 = (string) e.Attribute("prop1") };
I've generated MyObj
from the document itself, and setting every property within this document will be rather verbose when there's many of them. Is there some way to get Linq to work it out for itself?
Upvotes: 2
Views: 272
Reputation: 1063433
If you created the type via xsd.exe
(per the question), then the way to do this is with XmlSerializer
:
var ser = new XmlSerializer(typeof(MyObj));
var obj = (MyObj)ser.Deserialize(source);
You could try and do it with LINQ-to-XML, but it would really be re-implementing XmlSerializer
for very little purpose.
Upvotes: 2