cress cress - 1 month ago 11
C# Question

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.

I have this XML file:

<?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? Not sure how to get the next node.

I tried to print out
TagName
and
TagNum
inside a
foreach
loop like this:

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'

Answer

To get the date, just use .Element() to get the child:

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{}. You'll want to use var instead of string:

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