[英]Extracting XML data with Linq in C# difficulty
So I'm working with reading an xml file to create a dictionary, but I can't figure out how to access the xml fields I want. 因此,我正在阅读xml文件以创建字典,但是我不知道如何访问所需的xml字段。
Below is the format of the XML I want to read. 以下是我要阅读的XML格式。
<Days>
<Day Name="Monday">
<Task Order="1">TestTask</Task>
<Task Order="2">Test2</Task>
</Day>
</Days>
Below is my code so far. 下面是到目前为止的代码。 I've tried a lot of variations for finding task and order, such as for task: (string)e, or e.ToString(), or e.Elements("Task").Value.ToString(); 我已经尝试了许多查找任务和顺序的方法,例如任务:(string)e或e.ToString()或e.Elements(“ Task”)。Value.ToString(); And for order e.Attributes("Order").ToString(); 对于订单e.Attributes(“ Order”)。ToString();
string today = DateTime.Now.ToString("dddd");
var allItems = new Dictionary<string, int>();
XElement root = XElement.Parse(_orderxml);
IEnumerable<XElement> address =
from el in root.Elements("Day")
where el.Attribute("Name").Value == today
select el;
foreach (XElement e in address)
{
string task = ???;
string order = ???;
allItems.Add(task, (int)order);
}
So far, none of these have given me the right results, and I'm really unsure of what the proper way to get this data is, so any help would be appreciated! 到目前为止,这些方法都没有给我正确的结果,而且我真的不确定要获取此数据的正确方法是什么,因此将不胜感激!
Add a second loop to iterate the tasks and extract the values 添加第二个循环以迭代任务并提取值
static void Main()
{
string _orderxml = @"<Days> <Day Name=""Wednesday""> <Task Order=""1"">TestTask</Task> <Task Order=""2"">Test2</Task> </Day></Days>";
string today = DateTime.Now.ToString("dddd");
var allItems = new Dictionary<string, int>();
XElement root = XElement.Parse(_orderxml);
IEnumerable<XElement> address =
from el in root.Elements("Day")
where el.Attribute("Name").Value == today
select el;
foreach (XElement e in address)
{
foreach (XElement t in e.Descendants())
{
string task = t.Value.ToString();
int order = int.Parse(t.Attribute("Order").Value.ToString());
allItems.Add(task, (int)order);
}
}
}
Or you can do it with a Linq query like this 或者您可以使用这样的Linq查询来完成
var result=root.Descendants("Day").Where(d=>d.Attribute("Name").Value==today).Descendants("Task").Select(x => new {Task=x.Value,Order=x.Attribute("Order") });
Or create a dictionary from the anonymous objects 或从匿名对象创建字典
var result = root.Descendants("Day").Where(d=>d.Attribute("Name").Value==today).Select(x => new { Task = x.Value.ToString(), Order = x.Attribute("Order") }).ToDictionary(c => c.Task, c => c.Order);
Or create a dictionary directly from the linq query 或直接从linq查询创建字典
var result = root.Descendants("Day").Where(d=>d.Attribute("Name").Value==today).ToDictionary(c => c.Value.ToString(), c => int.Parse(c.Attribute("Order").Value.ToString()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.