2015-08-13 40 views
1

我是Xamarin的新手,我正在閱讀可移植類庫中的XML文件。在Xamarin中讀取XML文件

該文件既可以嵌入也可以在線,我已經做了一些研究並找到了兩種選擇,但是我發現的一切對於這樣一個簡單的任務來說過於複雜。我想知道如果有人有一個簡單,乾淨的方式來實現這一點。

唯一的規定是您使用可移植類庫,以便iOS,Android和Windows Phone項目都可以使用同樣的方法。

上下文: 基本上我正在建立一個項目列表,將被放置到ListViewer中。每個項目都有一個名稱字符串和一個ImageSource字符串。我有XML文檔,我想要使用的信息,我只需要一個簡單的方法來讀取Xamarin內的這些XML文件。

謝謝你提供的任何幫助!

回答

2

這是我的。我使用在線存儲的XML文件,將它們下載到Stream中,然後將Stream傳遞給XMLReader類。所有這些都是CrossPlatform代碼。

如果您想將@xml文件作爲應用程序資源嵌入,如@Dimitris Batsougiannis在其評論中解釋的那樣,這是第二種選擇。但是,一旦你有你的流,代碼將是相同的。簡單地說,將您的流傳遞給BuildItemList方法。

public class ItemHelper 
{ 
    public static bool IsReadingXML { get; set; } 
    public static List<Item> ItemList { get; set; } 

    public static void BeginReadXMLStream(string currFileName) 
    { 
     IsReadingXML = true; 

     string ImagesRootFolder = "http://www.mywebsite.com/"; 
     HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(ImagesRootFolder + currFileName); 
     httpRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), httpRequest); 
    } 

    private static void FinishWebRequest(IAsyncResult result) 
    { 
     IsReadingXML = true; 

     HttpWebResponse httpResponse = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse; 
     if (httpResponse.StatusCode == HttpStatusCode.OK) 
     { 
      Stream httpResponseStream = httpResponse.GetResponseStream(); 
      BuildItemList(httpResponseStream); 
     } 
    } 

    public static void BuildItemList(Stream xmlStream) 
    { 
     string ImagesRootFolder = "http://www.mywebsite.com/"; 
     List<Item> returnValue = new List<Item>(); 

     try 
     { 
      using (XmlReader myXMLReader = XmlReader.Create((xmlStream))) 
      { 
       while (myXMLReader.Read()) 
       { 
        if (myXMLReader.Name == "photo") 
        { 
         double tempPrice = 0.0; 
         double.TryParse(myXMLReader.GetAttribute("price"), out tempPrice); 

         returnValue.Add(new Item(
          myXMLReader.GetAttribute("info"), 
          tempPrice, 
          ImagesRootFolder + myXMLReader.GetAttribute("image"), 
          myXMLReader.GetAttribute("sku") 
          )); 
        } 
       } 
      } 
     } 
     catch { } 

     //Done 
     ItemList = returnValue; 
     IsReadingXML = false; 
    } 
} 
1

PCL無權訪問System.IO.File,但可以訪問System.IO.FileStream。

我認爲要解決你的問題是與StreamReader的添加XML文件在您的PCL的資源,在FileStream對象加載文件和讀取的一種方式,看看這篇文章

http://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/files/

儘管我建議你將文件轉換爲json,因爲我不知道XML解串器是否可用於PCL。

使用json,您可以使用json.net庫並輕鬆使用您的文件。

+0

感謝您對嵌入式文件文章的鏈接,我使用在線文件,您可以在下面看到我的答案。乾杯! – MattyMerrix

+0

@MattyMerrix如果我的文章幫助你,請務必點擊投票上傳/回覆。 –