0

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.

9
  • 1) Do you want to flatten your XDocument to your model? OR 2) Do you want to bind your model to list view? Commented Mar 28, 2019 at 5:54
  • @er-sho I want to parse the xml and bind it to my listview Commented Mar 28, 2019 at 5:57
  • @er-sho where iam stuck is creating a view model according to the xml and binding to the listview after parse Commented Mar 28, 2019 at 5:58
  • means you have 2 question in same post, could you please edit your post and ask these 2 question in different post. otherwise most likely your post has been marked as to broad by users. Commented Mar 28, 2019 at 6:18
  • @er-sho Bro sorry. My question is How can I make the xml to bind to the listview.Iam stuck at creating the data model Commented Mar 28, 2019 at 6:21

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

@Bro sorry for disturbing. Is my xaml bindings are correct?
@AndroDevil, Remember ?. is use for null checking and introduced in c# 6. If it gives you error on your side then simply remove it
@AndroDevil, not sure about xaml binding, because I mostly work on XML and Web API so its hard to say that, but you can find some way if you google it. Up to I'll consult with my xamarin collegues for any solution.
@AndroDevil, but above observable collection is most probably includes all your data in xml and I think you should use it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.