xdocument重写xml文档

时间:2015-12-09 19:42:06

标签: c# xml windows-store-apps windows-store

我想在按钮点击时通过我的 Windows商店应用编辑图片文件夹中的 xml文件

我使用了以下代码。

private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            StorageFolder storageFolder = KnownFolders.PicturesLibrary;
            StorageFile sampleFile = await storageFolder.GetFileAsync("q.xml");


            using (var fileStream = await sampleFile.OpenStreamForWriteAsync())
            {

                XDocument xdoc = XDocument.Load(fileStream);

                xdoc.Root.Add(new XElement("drink",
                 new XElement("drinkImage", "pepsi.png"),
                 new XElement("drinkTitle", "PEPSI"),
                 new XElement("drinkDescription", "HelloWorld")));
                xdoc.Save(fileStream);
            }

代码对我有用,但它重写了我的xml文件。

按钮之前单击我的xml文件:

<?xml version="1.0" encoding="utf-8"?>
<drinks>
  <drink>
    <drinkImage>ck.png</drinkImage>
    <drinkTitle>COKE</drinkTitle>
    <drinkDescription>(1793-1844)</drinkDescription>
  </drink>
  <drink>
    <drinkImage>pepsi.png</drinkImage>
    <drinkTitle>PEPSI</drinkTitle>
    <drinkDescription>HelloWorld</drinkDescription>
  </drink>
</drinks>

按钮后单击我的xml文件:

<?xml version="1.0" encoding="utf-8"?>
<drinks>
  <drink>
    <drinkImage>ck.png</drinkImage>
    <drinkTitle>COKE</drinkTitle>
    <drinkDescription>(1793-1844)</drinkDescription>
  </drink>
  <drink>
    <drinkImage>pepsi.png</drinkImage>
    <drinkTitle>PEPSI</drinkTitle>
    <drinkDescription>HelloWorld</drinkDescription>
  </drink>
</drinks>
  

//以上内容不应该在那里

    <?xml version="1.0" encoding="utf-8"?>
    <drinks>
      <drink>
        <drinkImage>ck.png</drinkImage>
        <drinkTitle>COKE</drinkTitle>
        <drinkDescription>(1793-1844)</drinkDescription>
      </drink>
      <drink>
        <drinkImage>pepsi.png</drinkImage>
        <drinkTitle>PEPSI</drinkTitle>
        <drinkDescription>HelloWorld</drinkDescription>
      </drink>
      <drink>
        <drinkImage>pepsi.png</drinkImage>
        <drinkTitle>PEPSI</drinkTitle>
        <drinkDescription>HelloWorld</drinkDescription>
      </drink>
    </drinks>

请帮助我完成这个重复。

预期文件是:

<?xml version="1.0" encoding="utf-8"?>
        <drinks>
          <drink>
            <drinkImage>ck.png</drinkImage>
            <drinkTitle>COKE</drinkTitle>
            <drinkDescription>(1793-1844)</drinkDescription>
          </drink>
          <drink>
            <drinkImage>pepsi.png</drinkImage>
            <drinkTitle>PEPSI</drinkTitle>
            <drinkDescription>HelloWorld</drinkDescription>
          </drink>
          <drink>
            <drinkImage>pepsi.png</drinkImage>
            <drinkTitle>PEPSI</drinkTitle>
            <drinkDescription>HelloWorld</drinkDescription>
          </drink>
        </drinks>

0 个答案:

没有答案