2015-02-05 67 views
1

我有一个XML文件损坏:的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声明必须是文档中的第一个节点,并且不允许在它之前出现空白字符。

这里是加载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); 
+0

这里是一个链接,你可以结帐https://social.msdn.microsoft.com/Forums/vstudio/en-US/e3f3c6b1-43ee-46d7-bc09-edb8dcedb8d1/add-node-existing-xml-file?论坛= csharpgeneral看起来像你不是添加'XmlNode',而是'XElement'而不是 – MethodMan 2015-02-05 20:42:29

+0

感谢您的响应,但您提供的链接有代码使用XML DOM添加节点,但我想用LINQ to XML来做相同。 – 2015-02-05 20:46:50

+0

如果在保存后打开它,XML文件是什么样的? – 2015-02-05 20:53:35

回答

1

你不显示所有的代码,但它看起来像你打开XML文件,从它读取XML到XDocument,编辑内存中的XDocument,然后回写到打开的流。由于数据流仍处于打开状态,因此它将位于文件的末尾,因此新的XML将被附加到文件中。

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

我(净使用的是旧版本),所以我不能对此进行测试,但类似以下应该从事的桌面代码只工作:

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 - https://stackoverflow.com/questions/13454584/writing-a-shorter-stream-to-a-storagefile 
       if (writer.CanSeek && writer.Length > 0) 
        writer.SetLength(0); 
       doc.Save(writer); 
      } 
     } 
    } 

此外,一定要create the file before using it

+1

谢谢...完美的作品。接受为答案。 – 2015-02-06 20:31:43