XmlTextReader,读取元素的子元素(或父元素?)



编辑:从XmlTextWriter切换到XElement

我有一个Player类,它有以下变量:

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

我已经用XElement将它们保存到Profiles.xml文件中,现在看起来是这样的:

<John>
    <level>3</level>
    <cash>215</cash>
</John>
<Mike>
    <level>7</level>
    <cash>780</cash>
</Mike>

如果我有name, fe。迈克,我怎么拿到钱和等级?

给你…

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"));
    }
}

使用xml序列化,这一切都将消失。

通用序列化:

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;
        }

和反序列化:

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);
    }

创建控制台应用程序并使用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);
        }
    }
}

相关内容

  • 没有找到相关文章