使用XML元素/属性进行xml反序列化 [英] xml deserialization using XML element/attributes

查看:203
本文介绍了使用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.

推荐答案


为了反序列化这种类型的XML,您需要组合对象:

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

[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


阅读文档可以学到很多东西
.NET Framework中的XML序列化 [
A lot can be learned from reading the documentation
XML Serialization in the .NET Framework[^]


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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆