.NET 4.x Спарсить содержимое тегов в xml - C#

Узнай цену своей работы

Формулировка задачи:

Всем доброго времени суток! Возникла потребность вытащить информацию заключенную в туги в файле xml пример кода:
<?xml version="1.0" encoding="UTF-8"?>
<server>
  <id>423666</id>
  <name>Имя сервера</name>
  <host>000.000.000.000</host>
  <port>2302</port>
  <version>1.63.125548</version>
  <required_version>163</required_version>
  <platform></platform>
  <state>playing</state>
  <mod>Mod_List</mod>
  <modhash></modhash>
  <mission>Mission</mission>
  <island>Map</island>
  <players>24</players>
  <created>2013-05-10 17:51</created>
  <updated>2015-02-09 18:51</updated>
  <gamename>gamename</gamename>
  <battleye>true</battleye>
  <signatures></signatures>
  <verify_signatures>false</verify_signatures>
  <passworded>false</passworded>
  <dedicated>true</dedicated>
  <game>
    <id>27958599</id>
    <mission>Mission</mission>
    <island>Chernarus</island>
    <start>2015-02-09 18:11</start>
    <end_time></end_time>
    <player_time>49572</player_time>
    <updated>2015-02-09 18:51</updated>
    <max_players>24</max_players>
    <players>
      <player>
        <id>447613229</id>
        <name>BlInZa [K-V]</name>
        <team></team>
        <connect_time>2015-02-09 18:13</connect_time>
        <disconnect_time></disconnect_time>
        <kills>0</kills>
        <deaths>0</deaths>
        <score>1</score>
      </player>
      <player>
        <id>447613230</id>
        <name>LaBomba</name>
        <team></team>
        <connect_time>2015-02-09 18:13</connect_time>
        <disconnect_time>2015-02-09 18:17</disconnect_time>
        <kills>0</kills>
        <deaths>0</deaths>
        <score>0</score>
      </player>
      <player>
        <id>447613231</id>
        <name>Tranquil [K-V]</name>
        <team></team>
        <connect_time>2015-02-09 18:13</connect_time>
        <disconnect_time></disconnect_time>
        <kills>0</kills>
        <deaths>0</deaths>
        <score>1</score>
      </player>
      <player>
        <id>447613232</id>
        <name>Pogranec</name>
        <team></team>
        <connect_time>2015-02-09 18:13</connect_time>
        <disconnect_time></disconnect_time>
        <kills>0</kills>
        <deaths>0</deaths>
        <score>15</score>
      </player>
      <player>
        <id>447613233</id>
        <name>[ROY]IIEnemYII</name>
        <team></team>
        <connect_time>2015-02-09 18:13</connect_time>
        <disconnect_time></disconnect_time>
        <kills>0</kills>
        <deaths>0</deaths>
        <score>0</score>
      </player>
      <player>
        <id>447613234</id>
        <name>Doker</name>
        <team></team>
        <connect_time>2015-02-09 18:13</connect_time>
        <disconnect_time>2015-02-09 18:39</disconnect_time>
        <kills>0</kills>
        <deaths>0</deaths>
        <score>8</score>
      </player>
      <player>
        <id>447613235</id>
        <name>Dimak</name>
        <team></team>
        <connect_time>2015-02-09 18:13</connect_time>
        <disconnect_time></disconnect_time>
        <kills>0</kills>
        <deaths>0</deaths>
        <score>5</score>
      </player>
      <player>
        <id>447613236</id>
        <name>[ROY]AJlAX </name>
        <team></team>
        <connect_time>2015-02-09 18:13</connect_time>
        <disconnect_time></disconnect_time>
        <kills>0</kills>
        <deaths>0</deaths>
        <score>0</score>
      </player>
      <player>
        <id>447613237</id>
        <name>VecToR_</name>
        <team></team>
        <connect_time>2015-02-09 18:13</connect_time>
        <disconnect_time></disconnect_time>
        <kills>0</kills>
        <deaths>0</deaths>
        <score>8</score>
      </player>
      <player>
        <id>447613238</id>
        <name>[F-S]Diman</name>
        <team></team>
        <connect_time>2015-02-09 18:13</connect_time>
        <disconnect_time></disconnect_time>
        <kills>0</kills>
        <deaths>0</deaths>
        <score>0</score>
      </player>
    </players>
  </game>
</server>
Нужно считать ники игроков заключенные в теги

<name>

.. куски откуда нужно вытащить:
<player>
        <id>447613238</id>
        <name>[F-S]Diman</name>
        <team></team>
        <connect_time>2015-02-09 18:13</connect_time>
        <disconnect_time></disconnect_time>
        <kills>0</kills>
        <deaths>0</deaths>
        <score>0</score>
      </player>
Попрошу не предлагать погуглить искать на форуме, т.к. не идиот и перед созданием поста облазил что только мог и ничего не работает!Заранее спасибо за помощь!
Вот код, который раньше работал 100%, но на данный момент не могу понять почему он не работает Класс:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
 
namespace RM_GUID
{
    class FlyingCircus
    {
        private XmlDocument server;
        private bool online = false;
        private string players = "0";
        private string playersOnline = "";
        private string version = "";
 
        public FlyingCircus()
        { 
            server = new XmlDocument();
            server.Load("http://arma2.swec.se/server/xml/423666.xml");
        }
 
        public void Refresh()
        {
            foreach (XmlNode task in server.DocumentElement.ChildNodes)
            {
                if (task.LocalName == "state")
                {
                    if (task.InnerText == "playing")
                    {
                        online = true;
                    }
                    else
                    {
                        online = false;
                        players = "0";
                        playersOnline = "";
                    }
                }
 
                else if (task.LocalName == "players" && online)
                    players = task.InnerText;
                else if (task.LocalName == "game" && online)
                {
                    foreach (XmlNode game in task.ChildNodes)
                    {
                        if (game.LocalName == "players")
                        {
                            foreach (XmlNode xmlPlayers in game.ChildNodes)
                            {
                                if (xmlPlayers.LocalName == "player")
                                {
                                    string tmp = "";
                                    bool disconnected = false; ;
                                    foreach (XmlNode player in xmlPlayers)
                                    {
                                        if (player.LocalName == "name")
                                        {
                                            tmp = player.InnerText;
                                        }
                                        else if (player.LocalName == "disconnect_time")
                                        {
                                            if (player.InnerText.Trim() != "")
                                            {
                                                disconnected = true;
                                            }
                                        }
                                    }
                                    if (!disconnected)
                                        playersOnline += tmp + " ";
                                }
                            }
                        }
                    }
                }
            }
        }
 
        public bool IsOnline()
        {
            return online;
        }
 
        public string PlayersCount()
        {
            return players;
        }
 
        public string PlayersOnline()
        {
            return playersOnline;
        }

        public string Ping()
        {
            Ping ping = new Ping();
            PingReply pingReply = null;
            pingReply = ping.Send("IP");
            if (pingReply.Status != IPStatus.TimedOut && online)
            {
                return pingReply.RoundtripTime.ToString();
            }
            else
                return "99999";
 
        }
 
    }
}
На форму:
FlyingCircus fc = new FlyingCircus();
                fc.Refresh();
                if (fc.IsOnline())
                    pictureBox1.Visible = true;
                else
                    pictureBox2.Visible = false;
                if (fc.IsOnline())
                    pictureBox2.Visible = false;
                else
                    pictureBox1.Visible = true;
                label9.Text = fc.PlayersCount();
                textBox3.Text = "Игроки онлайн: " + fc.PlayersOnline().Replace(" ", ",");

Решение задачи: «.NET 4.x Спарсить содержимое тегов в xml»

textual
Листинг программы
var players = String.Join(", ", server.SelectNodes(@"server/game/players/player/name").Cast<XmlElement>().Select(n => n.InnerText));

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

12   голосов , оценка 4.25 из 5