本文介绍了使用XML元素/属性进行xml反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在设置XML反序列化的xml属性时需要您的帮助.

这是我的输入xml:

Need your help in setting the xml attributes for XML deserialization.

This is my input xml:

<form>
<question id="QnA">
<answer>AnswerforA</answer>
</question>
<question id="QnB">
<answer>AnswerforB</answer>
</question>
<question id="QnC">
<answer>AnswerforC</answer>
</question>
</form>


每个问题元素标签的ID对应于一个类属性,其值是相应答案元素的内文.

.cs文件看起来像


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

 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

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

XmlReader xr = new xmlReader(inputxml);

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



请让我知道如何为Test类设置XML元素/属性以实现此目的.

感谢您的宝贵时间.



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

Thanks for your time.

推荐答案

[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:

XmlSerializer ser = new XmlSerializer(typeof(Form));
XmlReader xr = new xmlReader(inputxml);
Form t = ser.Deserialize(xr) as Form;



希望这对您有帮助



Hope this helps



这篇关于使用XML元素/属性进行xml反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 00:58