我正在尝试使用Linq To XML读取XML文件,但似乎无法理解如何操作。
我有这个XML文件:
<?xml version="1.0" encoding="utf-8" ?>
<Thing>
<Objects>
<MyTag name="" num="2">
<Date month="May" day="2" year="2006" />
</MyTag>
<MyTag name="" num="4">
<Date month="May" day="22" year="2012" />
</MyTag>
<MyTag name="" num="2">
<Date month="May" day="11" year="2034" />
</MyTag>
</Objects>
</Thing>
我从这个问题开始:
// Load the xml
XDocument document = XDocument.Load(XML_PATH);
var query = from thing in document.Root.Descendants("Objects")
select new
{
TagName = thing.Attribute("name").Value.ToString(),
TagNum = thing.Attribute("num").Value.ToString(),
// What do I write here to get the Date tag and attributes?
};
我如何获得Date
标记和属性?不知道如何获得下一个节点。
我尝试在TagName
循环中打印出TagNum
和foreach
,如下所示:
foreach(string value in query)
{
Console.WriteLine(value.TagName + " " + value.TagNum);
}
但是,我收到错误
CS0030 Cannot convert type '<anonymous type: string TagName, string TagNum>' to 'string'
答案 0 :(得分:2)
要获取日期,只需使用.Element()
来获取孩子:
from thing in document.Root.Descendants("Objects")
let date = thing.Element("Date")
select new
{
TagName = (string)thing.Attribute("name"),
TagNum = (string)thing.Attribute("num"),
DateMonth = (string)date?.Attribute("month"),
DateDay = (string)date?.Attribute("day"),
DateYear = (string)date?.Attribute("year"),
};
您的foreach
语句未编译,因为当query
集合属于new{}
返回的匿名类型时,您要求输入字符串。您需要使用var
代替string
:
foreach(var value in query)
{
Console.WriteLine(value.TagName + " " + value.TagNum);
}
答案 1 :(得分:1)
更改为var
类型,而不是string
foreach (var value in query)
{
Console.WriteLine(value.TagName + " " + value.TagNum);
}
答案 2 :(得分:1)
使用Element("elementName")
方法
var query =
document.Root
.Descendants("Objects")
.Select(obj => new
{
TagName = thing.Attribute("name").Value,
TagNum = thing.Attribute("num").Value,
Year = thing.Element("Date").Attribute("year").Value,
Month = thing.Element("Date").Attribute("month").Value,
Day = thing.Element("Date").Attribute("day").Value
};