Xml parse and binding to listview on xamarin forms

自闭症网瘾萝莉.ら 提交于 2021-02-11 13:27:42

问题


Hi I am trying to parse XML in my xamarin.forms app.The xml data contains one transactionID and couple of questions with multiple answers. What Iam trying to achieve is Bind the questions in to label and and answers into dropdowns in a listview.

The XML Iam getting from API

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<PlatformResponse>
  <TransactionDetails>
    <TransactId>39562</TransactionId>
  </TransactionDetails>
  <Response>
    <Questions>
      <Question type="1" text="Which one is correct?">
        <Answer correct="false">test1</Answer>
        <Answer correct="false">test2</Answer>
        <Answer correct="false">test3</Answer>
        <Answer correct="false">test4</Answer>
        <Answer correct="false">test5</Answer>
        <Answer correct="false">test5</Answer>  
      </Question>
      <Question type="2" text="Which one is associated with you?">
        <Answer correct="false">test1</Answer>
        <Answer correct="false">test2</Answer>
        <Answer correct="false">test3</Answer>
        <Answer correct="false">test4</Answer>
        <Answer correct="false">test5</Answer>
        <Answer correct="false">test5</Answer> 
      </Question>
      <Question type="3" text="Which one of the following is true ?">
         <Answer correct="false">test1</Answer>
        <Answer correct="false">test2</Answer>
        <Answer correct="false">test3</Answer>
        <Answer correct="false">test4</Answer>
        <Answer correct="false">test5</Answer>
        <Answer correct="false">test5</Answer> 
      </Question>
    </Questions>
  </Response>
</PlatformResponse>

How Iam parsing it

 HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
                    webRequest.ProtocolVersion = HttpVersion.Version10;
                    webRequest.Method = "POST";
                    webRequest.ContentType = "text/xml charset=utf8";
                    webRequest.ContentLength = postData.Length;
                    Stream requestStream = webRequest.GetRequestStream();
                    requestStream.Write(postData, 0, postData.Length);
                    requestStream.Close();
                    HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                    StreamReader reader = new StreamReader(webResponse.GetResponseStream());
                    string reader2 = reader.ReadToEnd();
                    List<XmlData> ObjXmlData = new List<XmlData>();
                    XDocument doc = XDocument.Parse(reader2);

           // How Can I bind it to the listview

My Data Model

   public class XmlData
     {
          public string TransactionId { get; set; }
          public string Question { get; set; }
          public string Answer { get; set; }        
     }

My List View

                <ListView  x:Name="QuestionsListView"  ItemsSource="{Binding}"
                     HasUnevenRows="True"                                                              
                     HorizontalOptions="FillAndExpand"
                     VerticalOptions="FillAndExpand">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <ViewCell>
                                <ViewCell.View>
                                    <StackLayout>
                                        <StackLayout Orientation="Horizontal">
                                            <Label Text="•" FontSize="Medium" TextColor="Green" Margin="0,20,0,0"/>
                                            <Label Text="{Binding Question}" FontSize="Small" TextColor="#474747" Margin="0,20,0,0">                                               
                                            </Label>
                                           </StackLayout>
                                            <StackLayout Orientation="Horizontal" Margin="10,0,10,0" HorizontalOptions="FillAndExpand" >                                             
                                            <Picker x:Name="picker1" Title="Select answer" ItemDisplayBinding="{Binding Answer}" HorizontalOptions="FillAndExpand" FontSize="Small" TextColor="Gray">
                                            </Picker>
                                            <Image Source="downarrow.png" HorizontalOptions="End" HeightRequest="20" WidthRequest="20" ></Image>
                                        </StackLayout>
                                    </StackLayout>
                                </ViewCell.View>
                            </ViewCell>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView

>

How Can I bind these questions and answers to picker and label. Any help appreciated.


回答1:


1) For your first question,

Below are the class models to parse your xml,

class Answer
{
    public string Text { get; set; }
    public bool Correct { get; set; }
}

class Question
{
    public string Ques { get; set; }
    public string Type { get; set; }
    public List<Answer> Answers { get; set; }
}

class Tranzaction
{
    public string TransactionId { get; set; }
    public List<Question> Questions { get; set; }
}

And by using LINQ to XML you can parse your xml to above class models like,

XDocument doc = XDocument.Parse("Your xml text here");

List<Tranzaction> transactions = (from p in doc.Descendants("PlatformResponse")
              select new Tranzaction
              {
                  TransactionId = p?.Elements("TransactionDetails")?.FirstOrDefault()?.Element("TransactionId")?.Value.Trim(),
                  Questions = (from q in p?.Descendants("Questions")?.Elements("Question")
                               select new Question
                               {
                                   Ques = q?.Attribute("text")?.Value,
                                   Type = q?.Attribute("type")?.Value,
                                   Answers = (from a in q?.Elements("Answer")
                                              select new Answer
                                              {
                                                  Text = a?.Value,
                                                  Correct = Convert.ToBoolean(a?.Attribute("correct")?.Value)
                                              }).ToList()
                               }).ToList()

              }).ToList();

2) For your second question,

Now you can create one ObservableCollection for above query result and bind it to list view in your xamarin form like

ObservableCollection<Tranzaction> tranzactionsOC = new ObservableCollection<Tranzaction>(transactions);

Now tranzactionsOC is your ObservableCollection and you can bind it to your xamarin form



来源:https://stackoverflow.com/questions/55390579/xml-parse-and-binding-to-listview-on-xamarin-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!