简体   繁体   中英

C# looping through Xelement

string webUrlCurrentGame = "";//usually the url 
var readerCurrentGame = JsonReaderWriterFactory.CreateJsonReader(
           Encoding.UTF8.GetBytes(webClient.DownloadString(webUrlCurrentGame)), 
           new System.Xml.XmlDictionaryReaderQuotas());
var currentGameRoot = XElement.Load(readerCurrentGame);
string gameMode = currentGameRoot.XPathSelectElement("//gameMode").Value;
string championId = currentGameRoot.XPathSelectElement("//championId").Value;
string SummonerName = currentGameRoot.XPathSelectElement("//summonerName").Value;

The problem is there are 10 summonerNames in the XML how do I get the value from all of them ?

with linq-to-xml often, if there's a singular verison of a selector, there's likely a plural version too.

In your case, currentGameRoot.XPathSelectElements("//summonerName") will return an IEnumerable which contains all the "summonerName" elements

Change

string SummonerName = currentGameRoot.XPathSelectElement("//summonerName").Value;

to

var SummonerNames = currentGameRoot.Descendants("summonerName")
                             .Select(sn => (string)sn)
                             .ToList();

If you use sn.Value and sn is null, you will get a NullExceptionError .

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