[英]How to convert multi-level xml into objects using 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內部各個對象的最佳方法是什么。 我知道我可能只是運行一個單獨的選擇,但我想知道是否有更好的方法來訪問它們所以我不必經歷兩次。
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")
返回名稱為“x”的所有子元素, Elements("x")
返回名稱為“x”的所有直接子Elements("x")
。
假設: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;}
}
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.