如何使用LINQ to XML将多级xml转换为对象?

时间:2013-04-22 22:22:15

标签: c# .net xml linq-to-xml

我的XML文件:

<myobject property1="foo" property2="bar">
    <property3>value1</property3>
    <property3>value1</property3>
    <property3>value1</property3>
</myobject>

我的C#代码:

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

如果您在xml文件中注意到我有3个元素需要与myobject元素及其属性一起转换为C#类。访问xml内部各个对象的最佳方法是什么。我知道我可能只是运行一个单独的选择,但我想知道是否有更好的方法来访问它们所以我不必经历两次。

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

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")返回名称为“x”的所有子元素,Elements("x")返回名称为“x”的所有直接子元素。

答案 2 :(得分:0)

假设:MyObject已被定义为类类型(见下文)。

然后,您可以按如下方式将xml反序列化为对象:

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;}
}

希望它有所帮助。

相关问题