简体   繁体   中英

How to convert multi-level xml into objects using LINQ to XML?

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.

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();
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".

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM