WP8解析XML格式文件

时间:2023-11-25 16:53:26

DOTA2 WebAPI请求返回的格式有两种,一种是XML,一种是JSON,默认是返回JSON格式,如果要返回XML格式的话,需要在加上format=xml。

这里举一个简单的解析XML格式的例子(更多XML操作):

<response>
<players>
<player>
<steamid>76561198092319753</steamid>
<communityvisibilitystate>1</communityvisibilitystate>
<profilestate>1</profilestate>
<personaname>偶买噶、Scohura</personaname>
<lastlogoff>1396240726</lastlogoff>
<profileurl>
http://steamcommunity.com/profiles/76561198092319753/
</profileurl>
<avatar>
http://media.steampowered.com/steamcommunity/public/images/avatars/f9/f90a468b223389164861722c599318216b388f18.jpg
</avatar>
<avatarmedium>
http://media.steampowered.com/steamcommunity/public/images/avatars/f9/f90a468b223389164861722c599318216b388f18_medium.jpg
</avatarmedium>
<avatarfull>
http://media.steampowered.com/steamcommunity/public/images/avatars/f9/f90a468b223389164861722c599318216b388f18_full.jpg
</avatarfull>
<personastate>0</personastate>
</player>
</players>
</response>

解析代码如下,输入Stream流转为String就是上面的文本

        private void prase(Stream xml)
{
userdata = XElement.Load(xml).Element("players").Element("player");
//昵称赋值、溢出部分使用省略号代替
username.Text = userdata.Element("personaname").Value;
username.TextTrimming = TextTrimming.WordEllipsis;
username.FontSize = (this.Height - )/;
//状态赋值
switch (userdata.Element("personastate").Value)
{
case "":
if (userdata.Element("communityvisibilitystate").Value.Equals(""))
{
statusText = "该用户已将资料设为隐私";
}
else
{
statusText = "离线";
}
break;
case "":
statusText = "在线";
break;
case "":
statusText = "忙碌";
break;
case "":
statusText = "离开";
break;
case "":
statusText = "打盹";
break;
case "":
statusText = "想交易";
break;
case "":
statusText = "想游戏";
break;
default :break;
}
status.Text = statusText;
status.FontSize = (this.Height - ) / ;
//状态辅助赋值
if (!userdata.Element("personastate").Value.Equals(""))
{
try
{
extraText = userdata.Element("gameextrainfo").Value + " 游戏中";
username.Foreground = new SolidColorBrush(Colors.Green);
status.Foreground = new SolidColorBrush(Colors.Green);
extra.Foreground = new SolidColorBrush(Colors.Green);
}
catch
{
username.Foreground = new SolidColorBrush(Colors.Blue);
status.Foreground = new SolidColorBrush(Colors.Blue);
extra.Foreground = new SolidColorBrush(Colors.Blue);
}
}
else
{
extraText = "上次在线时间:";
username.Foreground = new SolidColorBrush(Colors.Gray);
status.Foreground = new SolidColorBrush(Colors.Gray);
extra.Foreground = new SolidColorBrush(Colors.Gray);
}
extra.Text = extraText;
extra.FontSize = (this.Height - ) / ;
//头像赋值
BitmapImage bitImg = new BitmapImage(new Uri(userdata.Element("avatarfull").Value));
head.Source = bitImg;
}  

说明:

以XElement.Load(Stream xml)将Stream转化成XElement形式,而后其子标签,则使用XElement.Element(“Name”)获得,所对应的值为XElement.Value。