android – Xamarin: working with xml from resources

Question:

I am writing a project in Xamarin.Forms (for Android). Trying to load XML file from resources by command (from main project)

XDocument xdSave = XDocument.Load("save.xml");

But when executing, the error "File not found" appears. The file "save.xml" is added to the "Resources" folder of the .Droid project, marked as "AndroidResource"

I don't understand what the problem is Moreover, for example, pictures are loaded normally, the code

imgImage.Source = ImageSource.FromFile("drawable/icon.png");

works fine. In general, how to work with files from resources? Tell me please.

Answer:

Here is the documentation for resources in Xamarin / Android.

Resources are available by id, which in turn can be found in the Resource class (and spied in the Resource.designer.cs file). If your xml file is in the Resources/xml directory, the id should be available as Resource.xml.save or something similar.

Once you have an id, you can get XML from it using Resources.GetXml(id) . This will give you an XmlReader from which to build an XDocument :

XDocument.Load(Resources.GetXml(Resource.xml.save))

Maybe there is a more direct way, yes (I don't have anything to try on at hand).

Scroll to Top