Read XML file In MAUI project

1 Answer 3544 Views
General Discussions
Daniel
Top achievements
Rank 1
Silver
Bronze
Daniel asked on 01 Mar 2022, 03:59 PM

Hi,

Do you have example how I read XML file, where I need to put in MAUI project and how  I read it ?

Thanks in advance.

 

Daniel
Top achievements
Rank 1
Silver
Bronze
commented on 02 Mar 2022, 07:39 AM

Hi,

Thank you very much for the sample!!!

My problem is how to load this package (Microsoft.Maui.Essentials)  from NuGet Packages: manager

Which name I have to take., it not there.

This is your sample code:

 

This is my serach:

Thanks in advance,

Daniel
Top achievements
Rank 1
Silver
Bronze
commented on 02 Mar 2022, 07:45 AM

I used this :https://devblogs.microsoft.com/xamarin/xamarin-essentials-1-7-and-introducing-net-maui-essentials/

and I have <UseMaui>true</UseMaui> in the .csproj.

and add using using Microsoft.Maui.Essentials;

but is not work.

Lance | Manager Technical Support
Telerik team
commented on 02 Mar 2022, 02:33 PM

I only did a Visual Studio 2022 Preview > File > New  > MAUI project, I did not personally add any NuGet packages. Just double check that you are using the latest version of VS 2022 preview, and do a project Rebuild (not a Build). That will ensure the packages are restored from nuget.org before the code is compiled.

Regarding your link, that blog post is far too old. You want to keep in mind that .NET MAUI is a preview technology. Anything you read online right now has to be no older than 3-4 weeks, otherwise it very likely inaccurate. This is because .NET MAUI has a lot of changes every release, which is anout every 30 days. After it is officially released, then you can rely on everything being stable.

My recommendation is, during this preview period, only use the official Microsoft Documentation for MAUI

Daniel
Top achievements
Rank 1
Silver
Bronze
commented on 02 Mar 2022, 02:56 PM

I use VS 2022 as shown here, I rebuild the project and the package Microsoft.MAUI.Essentials not appear, I missed something.

Lance | Manager Technical Support
Telerik team
commented on 02 Mar 2022, 03:12 PM

Microsoft's NuGet packages do not come from Visual Studio, they come from nuget.org when you do a Rebuild or manual restore.

If you are not familiar with Visual Studio and using NuGet packages, I strongly recommend stop everything you're doing right now and follow this tutorial Install and use a NuGet package in Visual Studio | Microsoft Docs

Understanding how NuGet packages work is absolutely critical in understanding how to work with .NET projects like MAUI. That knowledge will also help you with other Visual Studio project types like ASP.NET Core, WPF and WinForms in a post-NET Framework world.

Daniel
Top achievements
Rank 1
Silver
Bronze
commented on 02 Mar 2022, 03:24 PM

I opened new MAUI project and now I have this package ,but  VS don't  recognize this :

 await using var stream = await FileSystem.OpenAppPackageFileAsync("Configuration.xml");

I tried to add using using Microsoft.Maui.Essentials;

also not help.

Daniel
Top achievements
Rank 1
Silver
Bronze
commented on 02 Mar 2022, 03:28 PM

What do I miss?
Lance | Manager Technical Support
Telerik team
commented on 02 Mar 2022, 04:37 PM

Hi Daniel, just use my attached project. There seems to be a problem with whatever project you're using, I can't tell you why packages are not restoring.

Also, you do not need to add a using statement (unless you've intentionally disabled global usings). What I suspect your problem is you are not restoring the packages or are not doing a Build/Rebuild.

Also, make sure the scope of the code editor in on the platform you're compiling for:

Keep in mind that MAUI is in preview and that tooling problems are expected to occur. When you encounter such issues, Microsoft asks that you report them so that they can work on it for the next preview release.

Here is how you can report a Visual Studio problem:

 

At this point, I'm afraid there isn't much Telerik Support can assist you with there. You're experiencing tooling issues that are outside the scope of what we can help with. You need the attention of the MAUI team or the Visual Studio team, open a new forum post in Microsoft Q&A so they can help you. (links in my answer)

Daniel
Top achievements
Rank 1
Silver
Bronze
commented on 03 Mar 2022, 07:51 AM | edited

I correct my self.

The file located in class library of dot net 5 and MAUI hosted it.

var  configurationXml = await File.ReadAllTextAsync(@"Configuration.xml");

When I read this file from volume D is ok.

But when I put the file in class library or MAUI I got excption.

Daniel
Top achievements
Rank 1
Silver
Bronze
commented on 03 Mar 2022, 07:55 AM

The exception:

Daniel
Top achievements
Rank 1
Silver
Bronze
commented on 03 Mar 2022, 11:45 AM

 This the results I found :
var locationOfTheDll = System.Reflection.Assembly.GetExecutingAssembly().Location;
            var locationOfTheXml = locationOfTheDll.Replace("Shared.dll", "Configuration.xml");
            var configurationXml = await File.ReadAllTextAsync(locationOfTheXml);
            return configurationXml;

Daniel
Top achievements
Rank 1
Silver
Bronze
commented on 03 Mar 2022, 12:56 PM

Can you please attach empty project with reference to TELERIK nuget call it

AutomationClient.MAUI. in net 6

The reason I have problem with my project.

Lance | Manager Technical Support
Telerik team
commented on 03 Mar 2022, 02:07 PM

Hi Daniel, that code is incorrect (it looks liek you copied it from a project that uses embedded resources). This is not how it work in .NET MAUI.

Instead, you can include the file in the project's Assets/Raw folder and make sure the file's BuildAction is set to MauiAsset.

I have no idea what the problem is you're having with general project structure, it is unrelated to Telerik UI for MAUI. For further assistance with this, I recommend working with the Microsoft, go to https://docs.microsoft.com/en-us/answers/topics/dotnet-csharp.html 

Daniel
Top achievements
Rank 1
Silver
Bronze
commented on 03 Mar 2022, 02:17 PM

The problem is that I read the file in Class library of net 5 and the hosted Environment of this library is MAUI.

I put the xml both in Class library of net 5 && In MAUI and I got this exception:

var configurationXml = await File.ReadAllTextAsync(@"Configuration.xml");
 and I got exception :

How is can be solved ?     

Daniel
Top achievements
Rank 1
Silver
Bronze
commented on 03 Mar 2022, 02:17 PM

I correct my self.

The xml file is located in Class library of dot net 5 and the hosted  in MAUI that used this class library.

var configurationXml = await File.ReadAllTextAsync(@"Configuration.xml");

When I read from D volume is ok but when I put  the xml in class library or MAUI

I got this exception.

Lance | Manager Technical Support
Telerik team
commented on 03 Mar 2022, 02:58 PM

Hi Daniel, the Telerik Forums cannot help you with that issue. Please open a post in the Microsoft Forums or StackOverflow using the links I have provided in my answer
Daniel
Top achievements
Rank 1
Silver
Bronze
commented on 07 Mar 2022, 07:19 AM

The problem solved like in your demo after uninstall and install VS 2022 preview version 2


/// <summary>
    /// Get configuration file data stracture
    /// </summary>
    /// <returns></returns>
    private async Task<string> GetConfigurations()
    {
        await using var stream = await FileSystem.OpenAppPackageFileAsync("Configurationxml");
        using var reader = new StreamReader(stream);
        var configurationXml = await reader.ReadToEndAsync();
        
        return configurationXml;

    }

1 Answer, 1 is accepted

Sort by
0
Lance | Manager Technical Support
Telerik team
answered on 01 Mar 2022, 04:13 PM | edited on 01 Mar 2022, 10:36 PM

Hi Daniel,

Telerik UI for MAUI is a set of UI components, whereas code that reads data from files is general .NET development topic (i.e. something you can do with the .NET and is not done with a UI component).

The Telerik forums and Telerik Support Ticket system are designed for getting assistance with the UI components themselves, not general development topics. To ask for help with general .NET development topics, you can search or post in the following locations:

Microsoft Documentation

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.

For example, I just did a quick Google/Bing search for "How do I load an XML file in C#" and this documentation was at the top => https://docs.microsoft.com/en-us/dotnet/standard/linq/load-xml-file. You can also find other good examples for the XmlReader docs => How to create a tree from an XmlReader - LINQ to XML | Microsoft Docs

 > Here is a nice little tutorial that shows you three different ways to load XML. I personally prefer the first option, but you'd need to have defined the classes ahead of time. If you do not want to setup classes, then I recommend option #2.

 

Demo

Attached is a demo I've written for you that contains some code to help you get started. It loads simple XML into a List<Book> . You can do whatever you want from there. For example, you could add Telerik components and then use the List with a DataGrid or anything else you want.

Regards,
Lance | Manager Technical Support
Progress Telerik

Love the Telerik and Kendo UI products and believe more people should try them? Invite a fellow developer to become a Progress customer and each of you can get a $50 Amazon gift voucher.

Lance | Manager Technical Support
Telerik team
commented on 01 Mar 2022, 04:25 PM

Amroun
Top achievements
Rank 1
commented on 31 Jan 2023, 01:52 PM

hello;
I used your example for my Maui application but I would like to select a line in your example in the list and this selection will take these data in another page; I used its
<Frame.GestureRecognizers>
                             <TapGestureRecognizer
                                 Tapped="TapGestureRecognizer_Tapped"/>
                         </Frame.GestureRecognizers>
but it doesn't work because it's xml file
Lance | Manager Technical Support
Telerik team
commented on 31 Jan 2023, 04:55 PM

Hi Amroun,

If you're using the CollectionView, I'm afraid I can't be of much assistance because that is a Microsoft control. You can ask for help form Microsoft about why TapGesture Recognizer doesn't work in a CollectionView here => .NET MAUI - Microsoft Q&A.

Instead, you should use the control's selection feature, a CollectionView has a SelectionChanged event.

private void BooksListControl_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var selectedBook = e.CurrentSelection as Book;
    Debug.WriteLine($"You have selected {selectedBook.Title}");
}

Precise Example

For a real example, I can show this using a Telerik UI for MAUI RadListView and our powerful SelectionChanged event. See this article for explanation and code examples => .NET MAUI ListView Documentation - Selection. I have also re-written my demo from scratch fo r you to see this in action.

First, lets review the layout:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:telerik="http://schemas.telerik.com/2022/xaml/maui"
             x:Class="SelectionExample.MainPage">
    <Grid RowSpacing="25"
          RowDefinitions="Auto, *"
          Padding="{OnPlatform iOS='30,60,30,30', Default='30'}">

        <Label x:Name="StatusLabel"
               Text="Loading..."
               FontSize="14"
               FontAttributes="Bold"
               HorizontalOptions="Center" />

        <telerik:RadListView x:Name="BooksListControl"
                             SelectionChanged="BooksListControl_OnSelectionChanged"
                             Grid.Row="1">
            <telerik:RadListView.ItemTemplate>
                <DataTemplate>
                    <telerik:ListViewTemplateCell>
                        <StackLayout Margin="0,0,0,10">
                            <Label Text="{Binding Title}" />
                            <Label Text="{Binding ISBN}" />
                            <Label Text="{Binding Price}" />
                        </StackLayout>
                    </telerik:ListViewTemplateCell>
                </DataTemplate>
            </telerik:RadListView.ItemTemplate>
        </telerik:RadListView>
    </Grid>
</ContentPage>

In the page's OnAppearing method, we load the data and in the SelectionChanged event we just show the selection

public partial class MainPage : ContentPage
{
    private readonly ObservableRangeCollection<Book> books = new();

	public MainPage()
	{
		InitializeComponent();
        
        BooksListControl.ItemsSource = books;
	}

    // When the page appears, check to see if we already have books loaded:
    // - If the books list is empty, then load data from XML file and add them to the list.
    // - If the books list is not empty, return.
    protected override async void OnAppearing()
    {
        base.OnAppearing();

        if (books.Any())
            return;

        StatusLabel.Text = "loading XML file...";

        await using var stream = await FileSystem.OpenAppPackageFileAsync("Books.xml");

        StatusLabel.Text = "Deserializing XML data...";

        var serializer = new System.Xml.Serialization.XmlSerializer(typeof(XmlData));

        var result = (XmlData)serializer.Deserialize(stream);
        
        var loadedData = result?.Books.ToList();

        switch (loadedData?.Count)
        {
            case 0:
                StatusLabel.Text = "No items were found in the data.";
                break;
            case > 0:
                StatusLabel.Text = $"{loadedData.Count} Books Loaded!";
                books.AddRange(loadedData);
                break;
            default:
                StatusLabel.Text = "Something went wrong";
                break;
        }

        StatusLabel.Text = "Data loaded! Awaiting selection...";
    }

    // When selection changes in the RadListView, read the first selected item's Title
    private void BooksListControl_OnSelectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.NewItems?.Count > 0 && e.NewItems[0] is Book selectedBook)
        {
            StatusLabel.Text = $"You have selected {selectedBook.Title}";
        }
    }
}

Here's a screenshot at runtime after selection:

Note: I know you want to navigate to a new page using that selection, for this you can research about .NET MAUI naviagtion here => .NET MAUI Shell navigation - .NET MAUI | Microsoft Learn.

General Advice

You never want to use a Gesture Recognizer in a list control that also has gesture recognition (selection, swipe, etc), this usually breaks any existing selection mechanism because it interferes with the internal mechanisms for selection. Either your recognizer will be broken, or the list control's will be broken.

I hope this helps clarify how you would handle selection. Please download and experiment with my demo to understand the setup further.

Amroun
Top achievements
Rank 1
commented on 03 Feb 2023, 10:43 AM

Thank you for your review, but I am missing the package for Telerik. I copied your NuGet.Config file in the root of my project but it does not recognize Telerik and useTelerik (); I tried to install the package but there are many, I don't know which one.

Thank you

Amroun
Top achievements
Rank 1
commented on 03 Feb 2023, 10:59 AM

Ah I found, I have to download
  Telerik UI for .NET MAUI. and install it
Amroun
Top achievements
Rank 1
commented on 03 Feb 2023, 12:51 PM

I installed the 30-day free version for Telerik for Maui but nothing has changed. I still have the same problem.

Severity Code Description Project File Line Suppression State
Error CS0246 The type or namespace name 'Telerik' could not be found (are you missing a using directive or an assembly reference?) TestSelectxml (net7.0-android), TestSelectxml (net7.0-ios), TestSelectxml (net7.0-maccatalyst), TestSelectxml
Severity Code Description Project File Line Suppression State
Error XLS0414 The type 'RadListView' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built. TestSelectxml

Severity Code Description Project File Line Suppression State
Error CS1061 'MauiAppBuilder' does not contain a definition for 'UseTelerik' and no accessible extension method 'UseTelerik' accepting a first argument of type 'MauiAppBuilder' could be found (are you missing a using directive or an assembly reference?) TestSelectxml (net7.0-android), TestSelectxml (net7.0-ios), TestSelectxml (net7.0-maccatalyst), TestSelectxml (net7.0-windows10.0.19041.0)

Lance | Manager Technical Support
Telerik team
commented on 03 Feb 2023, 01:18 PM

Amroun, please follow the Getting Started instructions, or more closely study my demo. My initial guess is you forgot to register the handlers in MauiProgram.cs.
Amroun
Top achievements
Rank 1
commented on 06 Feb 2023, 12:38 PM | edited

Hallo,

I did the Terelik installation steps but the last step for the package I did not have the Telerik.UI.for.Maui I sectioned the Telerik server and I wrote my user name and password but I have no result.

and here is my NuGet.config file

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
    <add key="telerik.com" value="https://nuget.telerik.com/v3/index.json" />
  </packageSources>
  <packageRestore>
    <add key="enabled" value="True" />
    <add key="automatic" value="True" />
  </packageRestore>
  <bindingRedirects>
    <add key="skip" value="False" />
  </bindingRedirects>
  <packageManagement>
    <add key="format" value="0" />
    <add key="disabled" value="False" />
  </packageManagement>
  <packageSourceCredentials>
    <telerik.com>
        <add key="Username" value="my-email-address" />
        <add key="Password" value="code-generated-by-progress-control-panel" />
      </telerik.com>
  </packageSourceCredentials>
</configuration>

 

[EDITED by Telerik Admin] - Removed sensitive information from configuration file.

Lance | Manager Technical Support
Telerik team
commented on 06 Feb 2023, 01:45 PM

Hi Amroun, that's strange. Just to make sure, I checked your account and indeed, you do not have any Telerik licenses on your account. This is why the Telerik NuGet server isn't giving you anything.

Please start a new trial license for Telerik UI for MAUI, then wait about 5-10 minutes for our NuGet server to sync up. You will then see Telerik.UI.for.Maui.Trial" in the feed (make sure you update my demo project to use the ".Trial" package name).

Alternatively, if your company purchased the license(s), then ask them to assign you as the Licensed User. This only take 10 seconds by using the Manage License Users portal.

Further Assistance

Are you here for Telerik UI for MAUI help? Or just asking for general .NET MAUI assistance? This forum is for the Telerik controls, this is why I am giving advice in the context of the Telerik UI for MAUI's RadListView and demonstrating its selection features. If you do not want this, then just replace the Telerik RadListView with a simpler Microsoft CollectionView (like my initial project for Daniel uses).

  • For assistance with general .NET topics, like CollectionView selection, File IO, etc, you can ask Microsoft for help here => .NET MAUI - Microsoft Q&A, you have two options:
  • For help with the Telerik controls, you have two options:

 

yasmina
Top achievements
Rank 1
Iron
commented on 06 Feb 2023, 09:05 PM

Hello again ;
thank you for your help, it works very well
yasmina
Top achievements
Rank 1
Iron
commented on 10 Feb 2023, 06:03 PM

Hallo,

can you help me I'm still working in the same project that you sent me for the list of an XML document for the selection of data it works, now I'm trying to download the xml of the list from Another file in the Android mobile is an update that is done every day for this list.

thank  you .

Lance | Manager Technical Support
Telerik team
commented on 10 Feb 2023, 06:21 PM

HI Yasmina, this is also not related to Telerik, so Telerik Support or Telerik UI for MAUI is unable to provide much assistance with it.

I have 3 places where you can ask for help:

If the XML file is from the internet, then you will want to ask for help with "HttpClient". If the file is somewhere else on the device, then you ask for help with "File system".

Quick Example

This is not an official Telerik-supported code snippet, it is a head start for you by showing you basic usage of HttpClient to download something from the internet, and then saves it to the local AppData folder. From here, you can use the Microsoft Documentation and ask for help in one of those 3 places I listed above.

private async Task<string> DownloadAndSaveMyXmlFile()
{
    var client = new HttpClient();
    byte[] xmlBytes = await client.GetByteArrayAsync("https://the-website-where-my-file-is.com/myfile.xml");
    string appdataDirectory = FileSystem.Current.AppDataDirectory;
    string filename = "myfile.xml";
    string filePath = Path.Combine(appdataDirectory, filename);
    await System.IO.File.WriteAllBytesAsync(filePath, xmlBytes);
    return filePath;
}

Amroun
Top achievements
Rank 1
commented on 13 Feb 2023, 08:39 AM

Hello Lance ,
Thank you for your help, for my project is that I have to load the document from another folder in the mobile, but I will understand the example you gave me but it is a download from the internet .and also I will contact the services (File system).

thank you very much for your answer.

Amroun
Top achievements
Rank 1
commented on 14 Feb 2023, 12:31 PM

hallo Lance, can you give me an example of Data Grid please because I made examples that there are in your documentation but it doesn't work; I believe I missed something. please.
Didi
Telerik team
commented on 14 Feb 2023, 12:49 PM

Hi Amroun, 
Could you please share what example is required? If you want to load data in the DataGrid from XML files, we have examples in our ControlsSample application. - DataGrid examples. The xml files are inside the Common folder : OrdersDataSource.xml and PeopleDataSource.xml. You can review the code and the implementation. Please note that how to read the file is up to you.

If you have issues populating the DataGrid with data, please open a separate ticket for this case and send us exact steps you did and code you used. Also share which examples from the documentation you have used? If there is an issue, I will address it. 

Thank you.

yasmina
Top achievements
Rank 1
Iron
commented on 14 Feb 2023, 01:31 PM

Hallo Didi ,

thank you for your cooperation,

I will explain a part of my project to you: I scan pieces  of big machines with the barecode in the first page and each machine contains different components for example the engine, the driver's cabin, Dcv ext ...
the scanner data will be filled in the Data Grid; after when all the parts of the machine are scanned they will be saved in the DataGrid and generate an XML file

Didi
Telerik team
commented on 14 Feb 2023, 03:18 PM

Hi,
I would like to ask you to open a support ticket and share more details on the setup you have. Also describe what is the exact issue with populating the DataGrid with data?

You populate the control with data and it is visualized in the cells. Then you can execute operations like filtering ,sorting ,grouping, editing the data in the control. If you want to generate xml file from the collection bound to the DataGrid ItemsSource, this is a custom logic implementation that must be done on your side.
Here are links that could be of help:   
https://stackoverflow.com/questions/8633398/xmlserialize-an-observablecollection 
and  https://stackoverflow.com/questions/39345073/how-to-convert-an-observablecollection-to-xml-file-from-c

yasmina
Top achievements
Rank 1
Iron
commented on 14 Feb 2023, 04:10 PM

How do I open a support ticket? please
Lance | Manager Technical Support
Telerik team
commented on 14 Feb 2023, 04:30 PM

Hi Yasmina,

It looks like you have not yet activated your Telerik account, this will prevent you from using certain features like professional technical support.

I have manually re-sent the activation email, please open that and confirm your account as soon as possible (check your spam folder if you don't see it). Once you've activated your account by confirming your email, you can move on with my instructions below.

My previous reply has instructions on how to open a Support Ticket, but I'll repeat the information here in a little more detail:

  1. Go to your Support Center page => https://www.telerik.com/account/support-center/
  2. Select "Contact Us"
  3. Select "Technical Support"

Please keep in mind that we may refer you to other help resources if your inquiries are not related to the Telerik controls.

yasmina
Top achievements
Rank 1
Iron
commented on 15 Feb 2023, 12:45 PM

I followed the steps you showed me in your last comment.
yasmina
Top achievements
Rank 1
Iron
commented on 15 Feb 2023, 12:45 PM

hallo Lance, I had the email to activate my Telerik account from the beginning but it always sends me this message:

Your Activation Link is Invalid

The activation link you have used is invalid.

Check the link in your email.

despite clicking on the link I received in my email

 

Lance | Manager Technical Support
Telerik team
commented on 15 Feb 2023, 03:13 PM

I'm sorry about that. The link is only good for a limited time. I just sent you a new activation email.
yasmina
Top achievements
Rank 1
Iron
commented on 16 Feb 2023, 02:55 PM

I tried one of your examples of DataGrid and it works but how to generate an XML file with DataGrid data
yasmina
Top achievements
Rank 1
Iron
commented on 16 Feb 2023, 02:56 PM

hallo Lance,

I apologize but I received no email to activate my account. I even looked in spam but there is nothing.

Didi
Telerik team
commented on 16 Feb 2023, 03:49 PM

 Hi Yasmina,

Regarding xml file generation from collection of data, I have send a reply in one of my previous posts. I am pasting it here: 

If you want to generate xml file from the collection bound to the DataGrid ItemsSource, this is a custom logic implementation that must be done on your side.
Here are links that could be of help:   
https://stackoverflow.com/questions/8633398/xmlserialize-an-observablecollection
and  https://stackoverflow.com/questions/39345073/how-to-convert-an-observablecollection-to-xml-file-from-c 

This question is not a specific question for the RadDataGrid control. As I explained this requires custom logic implementation. 

yasmina
Top achievements
Rank 1
Iron
commented on 20 Feb 2023, 03:18 PM

Hallo Lance ,

I have not yet had my email to activate my account; I am still waiting for a sign from you.

THANKS

Didi
Telerik team
commented on 22 Feb 2023, 11:00 AM

Hello Yasmina,

An activation link was sent to the email you use for the Telerik account. Please note that the link is only good for a limited time. If it expires, please reset your password for your Telerik account. 
Tags
General Discussions
Asked by
Daniel
Top achievements
Rank 1
Silver
Bronze
Answers by
Lance | Manager Technical Support
Telerik team
Share this question
or