[英]How to load xml file to xamarin android
我將Xml文件保存在Assets文件夾中,並在嘗試將更改保存到xml文件時將Build Action設置為Android Assets,它會給出異常System.UnauthorizedAccessException:拒絕訪問路徑“ /Q317664.xml”。我不確定為什么發生這種異常,請幫幫我
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.IO;
using System.Reflection;
using Android.Content.Res;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace App17
{
[Activity(Label = "App17", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
int count = 1;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
var xml = XDocument.Load(Assets.Open("Q317664.xml"));
var node = xml.Descendants("Book").FirstOrDefault(cd => cd.Attribute("Id").Value == "1");
node.SetAttributeValue("ISBN", "new");
xml.Save("Q317664.xml");
// Button button = FindViewById<Button>(Resource.Id.MyButton);
// button.Click += delegate { button.Text = string.Format("{0} clicks!", count++); };
}
}
}
應用程序捆綁包中的Assets
目錄是只讀的,您無法寫入打開的Q317664.xml
xml文檔。 這是System.UnauthorizedAccessException
的原因。
如果要修改資產目錄中捆綁的內容,請將其提取到可寫位置,然后對該副本進行操作:
string fileName = "Q317664.xml";
string filePath = Path.Combine (Android.OS.Environment.ExternalStorageDirectory.ToString (), fileName);
// Check if your xml file has already been extracted.
if (!File.Exists(filePath))
{
using (BinaryReader br = new BinaryReader(Assets.Open(fileName)))
{
using (BinaryWriter bw = new BinaryWriter(new FileStream(dbPath, FileMode.Create)))
{
byte[] buffer = new byte[2048];
int len = 0;
while ((len = br.Read(buffer, 0, buffer.Length)) > 0)
{
bw.Write (buffer, 0, len);
}
}
}
}
// Operate on the external file
var xml = XDocument.Load(filePath);
var node = xml.Descendants("Book").FirstOrDefault(cd => cd.Attribute("Id").Value == "1");
node.SetAttributeValue("ISBN", "new");
xml.Save("Q317664.xml");
看到:
您需要將XML文件添加到Xamarin Android項目中的Assets文件夾中
然后您可以像這樣將Xml加載到變量中
var xml = XDocument.Load(Assets.Open("data.xml"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.