簡體   English   中英

C#Linq to XML讀取具有屬性的多個標簽

[英]C# Linq to XML read multiple tags with attributes

我正在嘗試使用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標簽和屬性? 不確定如何獲取下一個節點。

我試圖在這樣的foreach循環中打印出TagNameTagNum

foreach(string value in query)
{
    Console.WriteLine(value.TagName + " " + value.TagNum); 
}

但是,我收到一個錯誤消息

CS0030  Cannot convert type '<anonymous type: string TagName, string TagNum>' to 'string'

要獲取日期,只需使用.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); 
}

像這樣更改它, var類型而不是string

 foreach (var value in query)
 {
    Console.WriteLine(value.TagName + " " + value.TagNum);
 }

使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM