C#循环遍历Xelement

时间:2016-06-08 20:59:46

标签: c# json xml

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;

问题是XML中有10个summonerNames如何从所有这些中获取值?

2 个答案:

答案 0 :(得分:0)

经常使用linq-to-xml,如果有一个选择器的单一版本,也可能有复数版本。

在您的情况下,currentGameRoot.XPathSelectElements("//summonerName")将返回包含所有“summonerName”元素的IEnumerable

答案 1 :(得分:0)

更改

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

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

如果您使用sn.Valuesn为空,则会获得NullExceptionError

相关问题