Linq关于复杂XML [英] Linq on Complex XML
问题描述
我有以下XML
<Feed>
<Control>
<Username>Fnol13</Username>
<Password>12345</Password>
</Control>
<Repairer>
<RepairerName>Test</RepairerName>
<RepairerAddress>Test</RepairerAddress>
<RepairerTelephone>Test</RepairerTelephone>
</Repairer>
</Feed>
以及包含以下属性的模型类
And a Model Class Containing following Properties
[Serializable]
public class Job {
public string Username { get; set; }
public string Password { get; set; }
public string Reference { get; set; }
public string RepairerAddress { get; set; }
public string RepairerTelephone { get; set; }
}
我正在使用以下Linq查询从XML提取数据
I am using following Linq Query to Extract Data from XML
var results = from job in xmlDoc.Descendants("Control")
select new Job {
Username = (string)job.Element("Username").Value,
Password = (string)job.Element("Password").Value
};
// Here I want to add as well Descendants("Repairer") using same query
return results.ToList();
问题在于可以返回 Descendants("Control").但是,我也想获得Descendants("Repairer"),并返回与模型显示相同的列表.您能帮我写Linq Query吗,我确认您是Linq的新人.
Problem is that can return Descendants("Control") However I would like to get also Descendants("Repairer") and return in a same list as my model is showing. Could you please help me to write Linq Query and I am confirming you I am very new in Linq.
推荐答案
您的模型Job
令我感到困惑,因为您可能有多个Control
&
Repairer
节点,在这种情况下,它应该映射到集合.无论如何,对于当前的XML我都假定您需要第一个Repairer
节点的元素,您可以这样实现:-
Your Model Job
looks confusing to me because you may have multiple Control
&
Repairer
nodes in which case it should map to a collection. Anyways for current XML I assume you need the elements of first Repairer
node, you can achieve it like this:-
var results = from job in xmlDoc.Root.Elements("Control")
let Repairer = job.Parent.Elements("Repairer").FirstOrDefault()
select new Job
{
Username = (string)job.Element("Username"),
Password = (string)job.Element("Password"),
RepairerName = (string)Repairer.Element("RepairerName"),
RepairerAddress = (string)Repairer.Element("RepairerAddress"),
RepairerTelephone = (string)Repairer.Element("RepairerTelephone")
};
此外,请注意(string)job.Element("Username")
将为您提供节点值.无需调用Value
属性.
Also, note (string)job.Element("Username")
will give you the node value. There is no need to call the Value
property.
更新:
使用LINQ-to-XML时可以使用XDocument
:-
You can use XDocument
when working with LINQ-to-XML:-
XDocument xmlDoc = XDocument.Load(XMLpath);
这篇关于Linq关于复杂XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!