question

mrizoiwe98 avatar image
0 Votes"
mrizoiwe98 asked JarvanZhang-MSFT answered

Writing to an XML file

Hello, I followed this tutorial on reading XML from a file. But I couldnt find any info how to write to an XML , even create new entries?


My code is similar to this

 var assembly = IntrospectionExtensions.GetTypeInfo(typeof(LoadResourceText)).Assembly;
 Stream stream = assembly.GetManifestResourceStream("WorkingWithFiles.LibXmlResource.xml");
 List<Monkey> monkeys;
 using (var reader = new System.IO.StreamReader (stream)) {
     var serializer = new XmlSerializer(typeof(List<Monkey>));
     monkeys = (List<Monkey>)serializer.Deserialize(reader);
 }
 var listView = new ListView ();
 listView.ItemsSource = monkeys;

Thank you

dotnet-xamarinforms
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi, mrizoiwe98. I created a basic demo to test the function, it works fine. First create a model class in the project. Then create the xml file according to the model class and set the Build Action to EmbeddedResource.

public class EmbeddedDataViewModel
{
    public EmbeddedDataViewModel()
    {
        DataCollection = new ObservableCollection<EmbeddedDataModel>();
        var assembly = IntrospectionExtensions.GetTypeInfo(typeof(EmbeddedDataTestPage)).Assembly;
        Stream stream = assembly.GetManifestResourceStream("TestApplication_5.TestData.xml");
        using (var reader = new StreamReader(stream))
        {
            var serializer = new XmlSerializer(typeof(ObservableCollection<EmbeddedDataModel>));
            DataCollection = (ObservableCollection<EmbeddedDataModel>)serializer.Deserialize(reader);
        }
    }
    public ObservableCollection<EmbeddedDataModel> DataCollection { get; set; }
}
0 Votes 0 ·
mrizoiwe98 avatar image mrizoiwe98 JarvanZhang-MSFT ·

Thanks but your example shows how to read from a file. I'm trying to write to a file.

0 Votes 0 ·

1 Answer

JarvanZhang-MSFT avatar image
0 Votes"
JarvanZhang-MSFT answered

I'm trying to write to a file.

Sorry for the mistake. But embedded resources are read only, we cannot edit the embedded file. To read and write to a file in Xamarin.Forms, try to achieve this on each native platform project.

Similar issue: https://stackoverflow.com/questions/29395367/xamarin-streamwriter/29395483#29395483

Related tutorials:
https://docs.microsoft.com/en-us/xamarin/android/platform/files/
https://docs.microsoft.com/en-us/xamarin/ios/app-fundamentals/file-system

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.