2016-06-08 133 views
1
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如何從所有這些值中獲取值?C#循環遍歷Xelement

+1

請包含您的XML(或從其派生的JSON),以便我們可以幫助您。 –

回答

0

經常使用linq-to-xml,如果有一個選擇器的單獨版本,那麼可能也有複數版本。

在你的情況,currentGameRoot.XPathSelectElements("//summonerName")將返回一個IEnumerable它包含了所有的 「summonerName」 元素

0

變化

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

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

如果使用sn.Valuesn爲空,你會得到一個NullExceptionError

+0

好吧,我已經改變了這一點,但現在我有問題返回值。起初我使用MessageBox.Show(SummonerName); – highwaydog

+0

如果你想從列表返回值然後使用MessageBox.Show(string.Join(「,」,SummonerName) – MethodMan