如何在C#中使用LINQ在XML文件中附加信息?

时间:2013-05-27 16:18:15

标签: c# xml linq windows-phone-7

我正在尝试在XML文件中写一些信息,结构应该是:

<Scoreboard>
 <Match>
  <name>Dummy</name>
  <score>1234</score>
 </Match>
 <Match>
  <name>Sample</name>
  <score>4567</score>
 </Match>    
</Scoreboard>

问题是我只能写一个条目,如果我插入另一个“匹配”,旧的条目会被覆盖。

例如,如果我有:

<Scoreboard>
 <Match>
  <name>Dummy</name>
  <score>1234</score>
 </Match>
</Scoreboard>

然后我想添加另一个条目,旧条目将被删除,我只会有新条目,例如:

<Scoreboard>
 <Match>
  <name>Sample</name>
  <score>4567</score>
 </Match>
</Scoreboard>

我知道如何在不覆盖旧条目的情况下编写新条目。

这是我的代码:

using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
        {
//If file doesn't exist, then create it.

            if (!isoStore.FileExists("scoreboard.xml"))
            {
                XDocument doc = new XDocument(new XElement("Scoreboard"));

                using (IsolatedStorageFileStream isoStream =
                   new IsolatedStorageFileStream("scoreboard.xml", System.IO.FileMode.Create, isoStore))
                {
                    doc.Save(isoStream);
                }


            }
            else
            {
//Else open it and write a new element which is a child of Scoreboard
                using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("scoreboard.xml", System.IO.FileMode.Open, isoStore))
                {
                    XDocument doc1 = XDocument.Load(isoStream);

                    var newElement = new XElement("Match",
                        new XElement("name", VarGlobal.Name),
                        new XElement("score", VarGlobal.Score));

                    doc1.Element("Scoreboard").Add(newElement);

                    Messaggio.Text = doc1.ToString();
                }
            }
        }

1 个答案:

答案 0 :(得分:1)

在这种情况下使用XmlSerializer会更有效,而不是手动推送xml中的元素。为记分卡对象建模并使用基本的Serializer和Deserializer。以下示例应该有效(假设您的操作方法称为SaveXmlValue())。

public class Match
{
    public string Name { get; set; }
    public string Score { get; set; }
}

public class Scorecard
{
    public List<Match> Match { get; set; }
}

public static Scorecard DeSerialize(Stream strm)
{
    var ser = new XmlSerializer(typeof(Scorecard));
    strm.Seek(0, SeekOrigin.Begin);
    return (Scorecard)ser.Deserialize(strm);
}

public static string Serialize(Scorecard scores)
{
    var ser = new XmlSerializer(typeof(Scorecard));
    using (var strm = new MemoryStream())
    {
        var writer = XmlWriter.Create(strm, new XmlWriterSettings() { Indent = true, Encoding = System.Text.Encoding.UTF8 });
        ser.Serialize(writer, scores);
        strm.Seek(0, SeekOrigin.Begin);
        var bytes = new byte[strm.Length];
        strm.Read(bytes, 0, (int)strm.Length);
        return System.Text.Encoding.UTF8.GetString(bytes, 0, bytes.Length);
    }
}

public void SaveXmlValue()
{
    Scorecard scores;
    if (isoStore.FileExists("scoreboard.xml"))
    {
        using (IsolatedStorageFileStream isoStream =
            new IsolatedStorageFileStream("scoreboard.xml", System.IO.FileMode.Open, isoStore))
        {
            scores = DeSerialize(isoStream);
        }
    }
    else
    {
        // Xml file doesn't exist, create new score card object
        scores = new Scorecard();
        scores.Match = new List<Match>();
    }

    scores.Match.Add(new Match() { Name = VarGlobal.Name, Score = VarGlobal.Score });

    var xml = Serialize(scores);
    using (IsolatedStorageFileStream isoStream =
            new IsolatedStorageFileStream("scoreboard.xml", System.IO.FileMode.Create, isoStore))
    {
        var buffer = System.Text.Encoding.UTF8.GetBytes(xml);
        isoStream.Write(buffer, 0, buffer.Length);
    }

}