2014-02-19 2 views
-1

Windows Phone 8 응용 프로그램의 C#에서 로컬 XML 파일을 편집하려고합니다. 웹에서 AppendChild과 같은 방법을 사용하여 XmlDocument을 사용하여 수많은 예제를 발견했습니다. Windows Phone 8에서 XmlDocumentXDocument으로, AppendChild은 사라졌습니다. 나는 아래의 코드를 시도했지만 protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)에 약간의 오류가 발생합니다 : 오류는 여기에서 볼 수있다 : http://i811.photobucket.com/albums/zz38/JelleK1996/cerror1_zpsb6aa5398.pngC# (WP8)에서 Xml 파일 편집

누구든지 나를 도울 수 있습니까?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Navigation; 
using Microsoft.Phone.Controls; 
using Microsoft.Phone.Shell; 
using XmlLocalEdit1.Resources; 
using System.Xml; 
using System.Xml.Linq; 
using System.Text; 

namespace XmlLocalEdit1 
{ 
    public partial class MainPage : PhoneApplicationPage 
    { 
     // Constructor 
     public MainPage() 
     { 
      InitializeComponent(); 

      // Sample code to localize the ApplicationBar 
      //BuildLocalizedApplicationBar(); 
     } 
     protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) 
     { 
      try 
      { 
       StringBuilder sb = new StringBuilder(); 
       XmlWriterSettings xws = new XmlWriterSettings(); 
       xws.OmitXmlDeclaration = true; 
       xws.Indent = true; 

       using (XmlWriter xw = XmlWriter.Create(sb, xws)) 
       { 
        XDocument xdoc = XDocument.Load("Resources/bar.xml"); 
        XElement xmlTree = new XElement("data", 
         new XElement("cocktail", 
          new XElement("name", "Dreamsicle"), 
          new XElement("id", 1) 
         ) 
        ); 
        xdoc.Add(xmlTree); 
        xdoc.Save(xw); 
       } 

       //xdoc.Add(xmlTree); 
       //xdoc.Save("Resources/bar.xml", SaveOptions.None); 

      } 
      catch (Exception myExc) 
      { 
       Console.WriteLine(myExc.Message); 
      } 
     } 

     /*private static XElement CreateCocktail(XDocument xmlDoc, 
               string name, 
               int id) 
     { 
      var xmlCocktail = xmlDoc 
     }*/ 
    } 
} 

XML 파일 :

<?xml version="1.0" encoding="UTF-8"?> 
<data> 
    <cocktail> 
    <name>43 Hedonism</name> 
    <id>14</id> 
    </cocktail> 
    <cocktail> 
    <name>B-52</name> 
    <id>4</id> 
    </cocktail> 
</data> 
+0

'아래 코드를 시도했지만 보호 된 무효 보이드에서 오류가 발생했습니다.'- '일부 오류'란 무엇입니까? – DGibbs

+0

오류 링크를 추가했습니다. http://i811.photobucket.com/albums/zz38/JelleK1996/cerror1_zpsb6aa5398.png – JelleKerkstra

+1

xml 파일은 어디에 있습니까? 그것은 리소스에있는 것처럼 보이며 확실하지 않습니다. Windows Phone에서 파일을 편집 할 수 있습니다. 이 파일을 편집하려면 격리 된 저장소로 복사 한 다음 해당 복사본으로 작업해야합니다. – Olter

답변

4

좋아요, 여기 샘플이 있습니다.

리소스에서 파일을 편집하는 대신 IsolatedStorage를 사용하는 것이 좋습니다.

  // copy the xml file to isolated storage 
      using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication()) 
      { 
       if (!file.FileExists("bar.xml")) 
       { 
        StreamResourceInfo sr_en = Application.GetResourceStream(new Uri("Resources\\bar.xml", UriKind.Relative)); 
        using (BinaryReader br_en = new BinaryReader(sr_en.Stream)) 
        { 
         byte[] data = br_en.ReadBytes((int)sr_en.Stream.Length); 
         //Write the file. 
         using (BinaryWriter bw = new BinaryWriter(file.CreateFile("bar.xml"))) 
         { 
          bw.Write(data); 
          bw.Close(); 
         } 
        } 
       } 

       // work with file at isolatedstorage 
       using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("bar.xml", FileMode.Open, file)) 
       { 
        XDocument doc = XDocument.Load(stream, LoadOptions.None); 

        // add new node to data section 
        doc.Descendants("data").FirstOrDefault().Add(
         new XElement("cocktail", 
          new XElement("name", "Dreamsicle"), 
          new XElement("id", 1) 
         ) 
        ); 
        // prevent xml file from doubling nodes 
        if (stream.CanSeek) 
         stream.Seek(0, SeekOrigin.Begin); 
        doc.Save(stream); 
       } 
      } 
+0

와우 감사합니다. 작동 중! – JelleKerkstra

+0

"예기치 않은 XML 선언 : XML 선언은 문서의 첫 번째 노드 여야하며 앞에 공백 문자를 사용할 수 없습니다. 선 11, 위치 10. IsolatedStorage에 xml 파일을 쓸 때 Byte Order Mark가 추가되었을 가능성이 있습니까? 그렇다면이 코드에서 어떻게 쉽게 삭제할 수 있습니까? – JelleKerkstra

+0

@ JelleKerkstra, 변경된 파일을 보려면 Visual Studio 용 격리 된 저장소 탐색기 확장을 사용해야합니다 (그 중 일부는 모두 무료입니다). 그러나 IS 탐색기는 실제 전화 장치 (주어진 스크린 샷, 에뮬레이터를 사용한다는 것을 보여줍니다)와 함께 작동하도록 만들어 지므로 일부 문제가 발생할 수 있습니다. 받은 오류는 " Olter

0

현재 코드는 유효한 XML 형식 아닌 여러 루트 요소가 포함 된 XML을 결과 xml 파일에 다른 <data> 요소를 추가합니다. 다른 <cocktail> 요소를 기존 <data> 요소에 대신 추가하고 싶습니다. 이 경우 다음과 같이 시도 할 수 있습니다.

....... 
XDocument xdoc = XDocument.Load("Resources/bar.xml"); 
XElement xmlTree = new XElement("cocktail", 
     new XElement("name", "Dreamsicle"), 
     new XElement("id", 1) 
    ); 
//add new <cocktail> to existing root, which is <data> element 
xdoc.Root.Add(xmlTree); 
xdoc.Save(xw); 
.......