![](/img/trans.png)
[英]How to load an XML file from a file in the solution, build with Embedded Resource? Project > Cross Platform > Xamarin.Forms
[英]How to load an XML file from a file in the solution, build with Embedded Resource?
這是我的解決方案的概述:
我已將構建設置為“嵌入式資源”,並且在生成應用程序時,XML文件未出現在/ Release文件夾中。 這是正確的,我想要這種行為。
現在,我正在嘗試將該文件加載到XDocument中,以便可以解析其中的數據:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Parsing XML.");
XDocument championXml = XDocument.Load("Champions.xml");
Console.ReadKey();
}
}
而且我收到文件未找到錯誤,因為它試圖在發布文件夾的完整路徑中找到xml文件。
如何將這些數據正確加載到XDocument中?
使用GetManifestResourceStream()
:
var asm = Assembly.GetExecutingAssembly();
using(var stream = asm.GetManifestResourceStream("Namespace.Champions.xml"))
{
// ...
}
可以通過調用GetManifestResourceNames()
找到用於引用資源的確切名稱。
直接引用資源屬性,並使用Parse代替load:
XDocument championXml = XDocument.Parse(Properties.Resources.ChampionsXML);
^^^^^^^^^^^^
//Name of your resource |
命名空間會有所不同,具體取決於您的項目結構。
您應該從匯編中獲得流:
Assembly.GetExecutingAssembly().GetManifestResourceStream(name)
其中的名稱將類似於:'LinqToXml.Champions.xml'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.