2015-02-05 5 views
1

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); 
+0

여기에 체크 아웃 할 수있는 링크가 있습니다. https://social.msdn.microsoft.com/Forums/vstudio/en-US/e3f3c6b1-43ee-46d7-bc09-edb8dcedb8d1/add-node-existing-xml-file? forum = csharpgeneral은 XmlNode 대신 XElement를 추가하는 것 같습니다. – MethodMan

+0

응답 해 주셔서 감사합니다.하지만 제공하신 링크에는 XML DOM을 사용하여 노드를 추가하는 코드가 있지만 XML에 LINQ를 사용하여 같은. –

+0

XML 파일을 저장 한 후 열면 XML 파일은 어떻게 생깁니 까? –

답변

1

당신은 당신의 모든 코드를 표시하지 않습니다,하지만 당신이 열처럼 보인다 XML 파일을 열고 XDocument에 XML을 읽고 메모리에 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

감사합니다 ... 완벽하게 작동합니다. 대답으로 수락됩니다. –