2015-02-05 66 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