Reputation: 7424
My XML File:
<myobject property1="foo" property2="bar">
<property3>value1</property3>
<property3>value1</property3>
<property3>value1</property3>
</myobject>
My C# Code:
List<MyObject> myObjectsInDB = (from f in xmlDoc.Descendants("myobject")
select new MyObject()
{
Property1 = f.Attribute("property1").Value,
Property2 = f.Attribute("property2").Value,
// Property3 = f.Element("property3").Value,
}).ToList();
If you notice in the xml file I have 3 elements that need to be converted into C# classes along with the myobject element and its attributes. What is the best way of accessing the individual objects inside of the xml. I know I could probably just run a separate select, but I was wondering if there was a better way of accessing them so I don't have to run through everything twice.
Upvotes: 1
Views: 2499
Reputation: 3323
Assumption: MyObject has already been defined as a class type (see below).
You can then deserialize your xml into an object as follows:
public static MyObject deserializeMyObject(){
var xmlString = @"<?xml version=""1.0"" ?><MyObject property1=""foo"" property2=""bar"">
<property3>value1</property3>
<property3>value1</property3>
<property3>value1</property3>
</MyObject>";
var xdoc=XDocument.Parse(xmlString);
XmlSerializer _s = new XmlSerializer(typeof(MyObject));
var foo= (MyObject)_s.Deserialize(xdoc.CreateReader());
return foo;
}
//assumption about the structure of your MyObject class
public class MyObject{
[XmlAttribute("property1")]
public string property1{get;set;}
[XmlAttribute("property2")]
public string property2 {get;set;}
[XmlElement]
public string[] property3 {get;set;}
}
Hope it helps.
Upvotes: 0
Reputation: 20054
var myobjects =
from myobjectEl in xdoc.Elements("myobject")
select new
{
Property1 = myobjectEl.Attribute("property1").Value,
Property2 = myobjectEl.Attribute("property1").Value,
Property3Texts =
(from prop3El in myobjectEl.Elements("property3")
select prop3El.Value).ToList(),
};
BTW: Descendants("x")
returns all child-elements with name "x", Elements("x")
returns all immediate children with name "x".
Upvotes: 1
Reputation: 35353
var result = xmlDoc.Descendants("myobject")
.Select(m => new
{
Property1 = m.Attribute("property1").Value,
Property2 = m.Attribute("property2").Value,
Property3 = m.Descendants("property3").Select(p3=>p3.Value).ToList()
})
.ToList();
Upvotes: 3