我有一個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);
這裏是一個鏈接,你可以結帳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
感謝您的響應,但您提供的鏈接有代碼使用XML DOM添加節點,但我想用LINQ to XML來做相同。 – 2015-02-05 20:46:50
如果在保存後打開它,XML文件是什麼樣的? – 2015-02-05 20:53:35