Xml 每次附加节点时都会损坏

Xml gets corrupted each time I append a node

我有一个 Xml 文件:

<?xml version="1.0"?>
<hashnotes>
  <hashtags>
    <hashtag>#birthday</hashtag>
    <hashtag>#meeting</hashtag>
    <hashtag>#anniversary</hashtag>
  </hashtags>
  <lastid>0</lastid>
  <Settings>
    <Font>Arial</Font>
    <HashtagColor>red</HashtagColor>
    <passwordset>0</passwordset>
    <password></password>
  </Settings>
</hashnotes>

然后我调用一个函数在 xml,

中添加一个节点

函数是:

public static void CreateNoteNodeInXDocument(XDocument argXmlDoc, string argNoteText)
    {
       string lastId=((Convert.ToInt32(argXmlDoc.Root.Element("lastid").Value)) +1).ToString();
       string date = DateTime.Now.ToString("MM/dd/yyyy");
        argXmlDoc.Element("hashnotes").Add(new XElement("Note", new XAttribute("ID", lastId), new XAttribute("Date",date),new XElement("Text", argNoteText)));
        //argXmlDoc.Root.Note.Add new XElement("Text", argNoteText)
        List<string> hashtagList = Utilities.GetHashtagsFromText(argNoteText);

        XElement reqNoteElement = (from xml2 in argXmlDoc.Descendants("Note")
                            where xml2.Attribute("ID").Value == lastId
                            select xml2).FirstOrDefault();
        if (reqNoteElement != null)
        {
            foreach (string hashTag in hashtagList)
            {
                reqNoteElement.Add(new XElement("hashtag", hashTag));
            }
        }

        argXmlDoc.Root.Element("lastid").Value = lastId;
    }

在此之后我保存 xml。 下次当我尝试加载 Xml 时,它失败并出现异常: System.Xml.XmlException: 意外的 XML 声明。 XML 声明必须是文档中的第一个节点,并且它之前不允许出现白色 space 字符。

这是加载 XML 的代码:

private static XDocument hashNotesXDocument;
private static Stream hashNotesStream;

StorageFile hashNoteXml = await InstallationFolder.GetFileAsync("hashnotes.xml");
hashNotesStream = await hashNoteXml.OpenStreamForWriteAsync();
hashNotesXDocument = XDocument.Load(hashNotesStream);

我使用以下方法保存它:

hashNotesXDocument.Save(hashNotesStream);

您没有显示所有代码,但看起来您打开了 XML 文件,将其中的 XML 读入 XDocument,编辑 XDocument 在内存中,然后写回打开的流。由于流仍处于打开状态,它将位于文件末尾,因此新的 XML 将附加到文件中。

建议消除 hashNotesXDocumenthashNotesStream 作为静态变量,而是打开并读取文件,修改 XDocument,然后使用显示的模式打开并写入文件 here.

我只在桌面代码上工作(使用较旧版本的 .Net),所以我无法对此进行测试,但类似以下内容应该可以工作:

    static async Task LoadUpdateAndSaveXml(Action<XDocument> editor)
    {
        XDocument doc;
        var xmlFile = await InstallationFolder.GetFileAsync("hashnotes.xml");
        using (var reader = new StreamReader(await xmlFile.OpenStreamForReadAsync()))
        {
            doc = XDocument.Load(reader);
        }        

        if (doc != null)
        {
            editor(doc);
            using (var writer = new StreamWriter(await xmlFile.OpenStreamForWriteAsync()))
            {
                // Truncate - 
                if (writer.CanSeek && writer.Length > 0) 
                    writer.SetLength(0);
                doc.Save(writer);
            }
        }
    }

此外,请务必create the file before using it