[英]C# Linq to XML read multiple tags with attributes
I am trying to read a XML file using Linq To XML but cannot seem to understand how to do it. 我正在尝试使用Linq To XML读取XML文件,但似乎无法理解该怎么做。
I have this XML file: 我有这个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>
I started with this query: 我从以下查询开始:
// 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?
};
How would I get the the Date
tag and attributes? 我如何获取
Date
标签和属性? Not sure how to get the next node. 不确定如何获取下一个节点。
I tried to print out TagName
and TagNum
inside a foreach
loop like this: 我试图在这样的
foreach
循环中打印出TagName
和TagNum
:
foreach(string value in query)
{
Console.WriteLine(value.TagName + " " + value.TagNum);
}
However, I am getting an error saying 但是,我收到一个错误消息
CS0030 Cannot convert type '<anonymous type: string TagName, string TagNum>' to 'string'
To get the date, just use .Element()
to get the child: 要获取日期,只需使用
.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"),
};
Your foreach
statement is not compiling because you're asking for strings when the query
collection is of the anonymous type returned by new{}
. 您的
foreach
语句未编译,因为当query
集合为new{}
返回的匿名类型时,您正在询问字符串。 You'll want to use var
instead of string
: 您将要使用
var
而不是string
:
foreach(var value in query)
{
Console.WriteLine(value.TagName + " " + value.TagNum);
}
Change it like this, var
type instead of string
像这样更改它,
var
类型而不是string
foreach (var value in query)
{
Console.WriteLine(value.TagName + " " + value.TagNum);
}
Use Element("elementName")
method 使用
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
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.