XmlTextReader, reading childelements (or parent element?) of an element

3.5k views Asked by At

EDIT: Switched from XmlTextWriter to XElement

I have a Player class, which has following variables:

static string Name;
static int Level;
static int Cash;

And I've saved them into a "Profiles.xml" file with XElement, it now looks like this:

<John>
    <level>3</level>
    <cash>215</cash>
</John>

<Mike>
    <level>7</level>
    <cash>780</cash>
</Mike>

Now if I have name, fe. Mike, how do I get the cash and level?

3

There are 3 answers

3
Gokul On BEST ANSWER

Here you go..

XDocument doc = XDocument.Parse(@"
<Players><John>
<level>3</level>
<cash>215</cash>
</John>
<Mike>
<level>7</level>
<cash>780</cash>
</Mike>
</Players>");

var players = doc.Root.Elements();

foreach (var player in players)
{
    if (player.Name.ToString() == "Mike")
    {
        Console.WriteLine(player.Element("level"));
        Console.WriteLine(player.Element("cash"));
    }
}
0
Kell On

Use xml serialisation and this will all go away.

To serialise generically:

public string Serialise(T someObject)
        {
            XmlSerializer ser = new XmlSerializer(typeof (T));
            MemoryStream memStream = new MemoryStream();
            XmlConfigTextWriter xmlWriter = new XmlConfigTextWriter(memStream, Encoding.UTF8);
            xmlWriter.Namespaces = true;
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", ""); //we don't want namespace data here.                
            ser.Serialize(xmlWriter, someObject, ns);
            xmlWriter.Close();
            memStream.Close();
            string xml = Encoding.UTF8.GetString(memStream.GetBuffer());
            xml = xml.Substring(xml.IndexOf(Convert.ToChar(60)));
            xml = xml.Substring(0, (xml.LastIndexOf(Convert.ToChar(62)) + 1));
            return xml;
        }

and to deserialise:

public T Deserialise(string objectXml)
    {
        XmlSerializer reader = new XmlSerializer(typeof (T));
        StringReader stringReader = new StringReader(objectXml);
        XmlTextReader xmlReader = new XmlTextReader(stringReader);
        return (T) reader.Deserialize(xmlReader);
    }
2
Damith On

Created console application and using LINQ to XML.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace ConsoleApplication8
{
    public class Player
    {
        public string Name { get; set; }
        public int level { get; set; }
        public int cash { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //  you may have several players like below 
            List<Player> Players = new List<Player>() { 
                new Player() { Name = "John", cash = 3, level = 215 }, 
                new Player() { Name = "Mike", level = 7, cash = 780 } 
            };

            // save them to Xml file 

            Save("players.xml", Players);

            //when you need details of a given player "Mike"
            Player PlayersMike = Load("players.xml", "Mike");

            // Adding new player 

            AddPlayer("players.xml", new Player() { Name = "Test", level = 1, cash = 780 });


        }

        /// <summary>
        /// Saves the specified XML file with players data
        /// </summary>
        /// <param name="xmlFile">The XML file.</param>
        /// <param name="Players">The players.</param>
        public static void Save(string xmlFile, List<Player> Players)
        {
            XElement xml = new XElement("Players",
                            from p in Players
                            select new XElement("Player",
                                 new XElement("Name", p.Name),
                                new XElement("level", p.level),
                                new XElement("cash", p.cash)));

            xml.Save(xmlFile);

        }

        /// <summary>
        /// Loads the specified XML file.
        /// </summary>
        /// <param name="xmlFile">The XML file.</param>
        /// <returns></returns>
        public static Player Load(string xmlFile, string name)
        {
            XDocument doc = XDocument.Load(xmlFile);

            var query = (from xElem in doc.Descendants("Player")
                        where xElem.Element("Name").Value.Equals(name)
                        select new Player
                        {
                            Name = xElem.Element("Name").Value,
                            level = int.Parse(xElem.Element("level").Value),
                            cash =  int.Parse(xElem.Element("cash").Value),
                        }).FirstOrDefault();
            return query;
        }

        /// <summary>
        /// Adds the player.
        /// </summary>
        /// <param name="xmlFile">The XML file.</param>
        /// <param name="p">The p.</param>
        public static void AddPlayer( string xmlFile, Player p)
        {
            XDocument doc = XDocument.Load(xmlFile);
            doc.Element("Players").Add(
                new XElement("Player",
                                 new XElement("Name", p.Name),
                                new XElement("level", p.level),
                                new XElement("cash", p.cash)));
            doc.Save(xmlFile);
        }
    }
}