【问题标题】:C# Linq to XML read multiple tags with attributesC# Linq to XML 读取多个带有属性的标签
【发布时间】:2017-02-17 02:57:43
【问题描述】:

我正在尝试使用 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'

【问题讨论】:

  • 使用foreach (var value in query)

标签: c# xml linq parsing


【解决方案1】:

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

【讨论】:

  • 感谢您的解释。从中学到了很多。
【解决方案2】:

使用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  
            };

【讨论】:

    【解决方案3】:

    改成这样,var 输入而不是string

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

    【讨论】:

    • 谢谢。认为查询中的所有内容都是字符串。
    猜你喜欢
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多