简体   繁体   中英

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'

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); 
}

Change it like this, var type instead of string

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

Use Element("elementName") method

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM