简体   繁体   中英

How to query XML with the same element and attribute name using linq

I have successfully extract all the data I needed but I realise that my array list was not consistent due to the fact that not all the player has the same Stat.

XML File:

<Team ID="3">
    <Player ID="p24">
        <Name>Kobe Bryant</Name>
        <Position>Forward-Guard</Position>
        <Stat Type="firstname">Kobe</Stat>
        <Stat Type="lastname">Bryant</Stat>
        <Stat Type="birthdate">1978-08-31</Stat>
        <Stat Type="birthplace">USA</Stat>
        <Stat Type="firstnationality">USA</Stat>
        <Stat Type="weight">212</Stat>
        <Stat Type="height">6'6</Stat>
        <Stat Type="jerseynum">24</Stat>
        <Stat Type="realposition">Forward-Gaurd</Stat>
        <Stat Type="realpositionside">Unknown</Stat>
        <Stat Type="joindate">1996-07-28</Stat>
        <Stat Type="country">USA</Stat>
    </Player>
    <Player ID="p30">
        <Name>Nick Young</Name>
        <Position>Forward-Guard</Position>
        <Stat Type="firstname">Nick</Stat>
        <Stat Type="lastname">Young</Stat>
        <Stat Type="birthdate">1985-06-01</Stat>
        <Stat Type="weight">210</Stat>
        <Stat Type="height">6'7</Stat>
        <Stat Type="jerseynum">30</Stat>
        <Stat Type="realposition">Forward-Guard</Stat>
        <Stat Type="realpositionside">Unknown</Stat>
        <Stat Type="joindate">2015-07-02</Stat>
        <Stat Type="country">USA</Stat>
    </Player>
    <TID>ARS</TID>
    <Stadium ID="350">
        <Capacity>19000</Capacity>
        <Name>Staples Center</Name>
    </Stadium>
    <TeamOfficial Type="Assistant Manager" ID="AM56" country="USA">
        <PersonName>
            <BirthDate>1975-11-16</BirthDate>
            <First>Mark</First>
            <Last>Madsen</Last>
            <join_date>2014-07-01</join_date>
        </PersonName>
    </TeamOfficial>
    <TeamOfficial Type="Assistant Coach" ID="AC51" country="USA">
        <PersonName>
            <BirthDate>1968-10-22</BirthDate>
            <First>Jim</First>
            <Last>Eyen</Last>
            <join_date>1999-09-30</join_date>
        </PersonName>
    </TeamOfficial>
</Team>

C# Code:

XDocument xDoc = XDocument.Load("test.xml");

var TeamQ = from T in xDoc.Descendants("Team")
            where (string)T.Attribute("ID") == "3"
            from P in T.Elements("Player")
            let fn = P.Elements("Stat")
            select new
            {
                PlayerTeamID = (string)P.Attribute("ID"),
                Position = (string)P.Element("Position"),
                Stats = fn.Select(x => (string)x.Value)
                .ToList()

            };

            foreach (var tP in TeamQ)
            {
                listBox.Items.Add(tP.PlayerTeamID);              
            }

I would like to store these data in a list of objects. But when I tried to store the values in the class properties the data is inconsistent due to the fact there are some elements missing. for eg if I try to store the first nationality in the class when it reaches the second player it will store the height of the second player.

Try to use a Dictionary for stats instead of a List:

XDocument xDoc = XDocument.Load(@"c:\test.xml");
var TeamQ = from T in xDoc.Descendants("Team")
            where (string)T.Attribute("ID") == "3"
            from P in T.Elements("Player")
            let fn = P.Elements("Stat")
            select new
            {
                PlayerTeamID = (string)P.Attribute("ID"),
                Position = (string)P.Element("Position"),
                Stats = fn.Select(x => 
                                  new { key = x.Attribute("Type").Value
                                                                 .ToString(), 
                                        val = x.Value.ToString() })
                          .ToDictionary(k => k.key, 
                                        var => var.val, 
                                        StringComparer.OrdinalIgnoreCase)
            };

foreach (var tP in TeamQ)
{
    Console.WriteLine(tP.PlayerTeamID);
    //example how to get a value for a key
    if (tP.Stats.ContainsKey("firstnationality"))
    {
       Console.WriteLine(tP.Stats["firstnationality"]);  
    }
    else
    {
        Console.WriteLine("\"firstnationality\" not found");  
    }

    //example output all key->values pairs 
    foreach (var st in tP.Stats)
    {
        Console.WriteLine("{0}=>{1}",st.Key,st.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