I 노드를 추가 할 때마다 손상되면 : 나는 다음 XML에 노드를 추가하는 함수를 호출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>
을
기능은 다음과 같습니다
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? forum = csharpgeneral은 XmlNode 대신 XElement를 추가하는 것 같습니다. – MethodMan
응답 해 주셔서 감사합니다.하지만 제공하신 링크에는 XML DOM을 사용하여 노드를 추가하는 코드가 있지만 XML에 LINQ를 사용하여 같은. –
XML 파일을 저장 한 후 열면 XML 파일은 어떻게 생깁니 까? –