【问题标题】:xml XDocument Save modify filexml XDocument 保存修改文件
【发布时间】:2017-02-06 22:49:48
【问题描述】:

我正在尝试将XElements 添加到XDocument。我正在尝试从使用 inifile 转移到 xml,但我在这里遇到了一些问题。

这是我的C# 代码:

public static async Task<List<XElement>> XMLHandling()
        {
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
            StorageFile file = await storageFolder.GetFileAsync("sFile.xml");

            List<XElement> doc;
            using (var fileStream = await file.OpenStreamForReadAsync())
            {
                doc = XDocument.Load(fileStream).Descendants("signals").ToList();
                //avoid range check
                doc[0].Add(new XElement("Character", new XElement("Value", "value1"), new XElement("Description", "This is some text")));
                using (Stream sr = await file.OpenStreamForWriteAsync())
                {
                    doc[0].Save(sr);
                }
            }
            //example
            return doc;
        }

这是文件之前的样子:

<?xml version="1.0"?>
<catalog>
   <signals>

   </signals>

   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
</catalog>

之后是这样的:

<?xml version="1.0" encoding="utf-8"?>
<signals>
  <Character>
    <Value>value1</Value>
    <Description>This is some text</Description>
  </Character>
</signals>/title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
</catalog>

我什至不明白为什么,也无法调试。 有什么想法吗?

【问题讨论】:

  • 请发布您期望的输出。不是你得到的。

标签: c# xml linq xelement


【解决方案1】:

这里至少有两个问题。

首先,你并没有保存你的本来面目。

doc = XDocument.Load(fileStream).Descendants("signals").ToList();

这里,docsignals 元素的列表。

doc[0].Add(new XElement("Character", new XElement("Value", "value1"), 
    new XElement("Description", "This is some text")));

在这里,您将Character 元素添加到第一个signals 元素。

doc[0].Save(sr);

最后,您保存第一个signals 元素。这就解释了为什么您会在“新”文档的开头看到 signals

其次,您不会截断正在写入的文件。这就是为什么您在 signals 元素末尾看到一些乱码的 XML - 这只是文件中最初的内容,您刚刚覆盖了它的第一部分。您可能希望查看this question 以了解处理此问题的一些选项。一种选择是在写入之前将长度设置为零。

所以,是这样的:

XDocument doc;

using (var stream = await file.OpenStreamForReadAsync())
{
    doc = XDocument.Load(stream);
}

var signals = doc.Descendants("signals").Single();

signals.Add(new XElement("Character", ...));

using (var stream = await file.OpenStreamForWriteAsync())
{
    stream.SetLength(0);
    doc.Save(stream);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-23
    • 1970-01-01
    • 2014-06-09
    • 2014-05-03
    • 2015-11-30
    • 2017-07-07
    • 1970-01-01
    相关资源
    最近更新 更多