Home > Mobile >  Load XML file to MAUI project
Load XML file to MAUI project

Time:12-22

I am trying to load from XML file and parse it from Resources/Raw folder in project to MAUI app right at the beginning so that any class and screen can access this parsed XML file.

public static MauiApp CreateMauiAppAsync()
    {
        var builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp<App>()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
            });


        string path;

        Device.BeginInvokeOnMainThread(async () =>
        {
            path = await ReadResources();
            List<Siren> sirens = ParseXML(path);
        });        

        return builder.Build();
    }

    private static Task<string> ReadResources()
    {
        var stream = FileSystem.OpenAppPackageFileAsync("file.xml");
        var reader = new StreamReader(stream.Result);

        Task.Run(() =>
        {
            return reader.ReadToEnd();
        });

        throw new FileLoadException();
    }
...

I have this line of code in my .csproj file <MauiAsset Include="Resources\Raw\*" /> and in App.xaml I have this:

...
<ResourceDictionary Source="Resources/Styles/Styles.xaml" />
<ResourceDictionary Source="Resources/Raw/file.xml" />
...

along with default fonts.

error of this program is:

Resource "Resources/Raw/file.xml" not found

I am new to MAUI and I need to know how to parse XML at the start of the app so that other classes can access parsed XML in array.

CodePudding user response:

You can check this article about How to deserialize xml document in C#.You will also find a lot of good resources in the Microsoft Documentation for C#. Since .NET MAUI uses .NET 6, you will find a significant level of compatibility with any code you find.You can check this article How to load XML from a file (LINQ to XML) for a reference.

CodePudding user response:

To include files from Resources/Raw I don't use ResourceDictionary, I just have the following in my .csproj:

<ItemGroup>
<MauiAsset Include="Resources\Raw\**" LogicalName="%(RecursiveDir)%(Filename)%(Extension)" />
</ItemGroup>

That copies all the files in the Raw directory (including folder structure beneath Raw) so I can access them using OpenAppPackageFileAsync. For some reason, however, occasionally there also ends up a line farther down in the .csproj with a Remove for specific files, like:

<ItemGroup>
    <MauiAsset Remove="Resources\Raw\file.xml" />
</ItemGroup>

If I don't delete those I get a Resource not found error.

  • Related