Click here to Skip to main content
14,924,665 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
Need your help in setting the xml attributes for XML deserialization.

This is my input xml:
XML
<form>
<question id="QnA">
<answer>AnswerforA</answer>
</question>
<question id="QnB">
<answer>AnswerforB</answer>
</question>
<question id="QnC">
<answer>AnswerforC</answer>
</question>
</form>

The ids of each question element tag correspond to a class property and its value is the innertext of the corresponding answer element.

The .cs file will look like

C#
 public class Test
{

   private string qnaAns;
   private string qnbAns;
   private string qncAns;

    public string QnA
    {
    get{ return qnaAns;}
    set{qnaAns = value;}
    }

    public string QnB
    {
    get{ return qnbAns;}
    set{qnbAns = value;}
    }

    public string QnC
    {
    get{ return qncAns;}
    set{qncAns = value;}
    }
}


and I use the following code for deserialization

C#
XmlSerializer ser = new XmlSerializer(typeof(Test));

XmlReader xr = new xmlReader(inputxml);

Test t = ser.Deserialize(xr) as Test;


Please let me know how to set the XML element/attribute for the Test class to achieve this.

Thanks for your time.
Posted
Updated 17-Oct-11 5:34am
v2

Hi,
In order to deserialize this type of XML you would need composed objects:

C#
[Serializable]
public class Question
{
[XmlAttribute] public string id; //render as Xml Attribute
public string answer; //default rendering as Xml Element
}

[Serializable]
public class Form
{
[System.Xml.Serialization.XmlElementAttribute("question")] 
public Question [] question; 
}

Then try to desirialize:
C#
XmlSerializer ser = new XmlSerializer(typeof(Form));
XmlReader xr = new xmlReader(inputxml);
Form t = ser.Deserialize(xr) as Form;


Hope this helps
   
Comments
Member 8004095 17-Oct-11 22:55pm
   
Hi,

Thanks for your reply. But still I have to iterate through the question to set/get the QnA property.

I changed the line "Question []" to "List<question>"

public string QnA
{
get { return question[question.FindIndex(t=>t.id=="QnA")].answer;}
set { ; }
}

Is it possible to set the properties (QnA, QnB, QnC) directly by specifying the xmlelement/attributes?

Also, is it possible to specify another parameter "section" along with "question" for the question object i.e

The form can also be

<form>
<question id="QnA">
<answer>AnswerforA


<answer>AnswerforB

</form>

Many thanks for your time.
A lot can be learned from reading the documentation
XML Serialization in the .NET Framework[^]
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900