【问题标题】:How to specify the XML element tag to include all the specified xml nodes in deserialization如何在反序列化中指定 XML 元素标记以包含所有指定的 xml 节点
【发布时间】:2011-10-18 15:33:04
【问题描述】:

我在下面的链接中得到了序列化我的课程的答案

XML de-serialization using xml element/attributes

但我必须包含所有元素,无论它们在 XML 中的位置如何。

XML:

     <form>
     <question id="QnA">
        <answer>AnswerforA</answer>
     </question>
     <question id="QnB">
        <answer>AnswerforB</answer>
     </question>
     <question id="QnC">
        <answer>AnswerforC1</answer>
     </question>
     <section>
         <question id="Qnd">
           <answer>Answerford</answer>
         </question>
      </section>
    </form>

.cs:

  [XmlRoot("form")]
  public class Form
  {
        [XmlElement("question")]
        public List<Question> Questions { get; set; }

        public Form()
        {
              Questions = new List<Question>();
        }
  }
  public struct Question
  {
        [XmlAttribute("id")]
        public string ID { get; set; }

        [XmlElement("answer")]
        public string Answer { get; set; }
  }

在此,我可以得到问题列表中的三个元素QnA,QnB,QnC。

如何指定 XML 元素,使其包含下的所有问题元素,即将 QnD 元素也包含在列表中。

谢谢

【问题讨论】:

    标签: c# .net xml xml-serialization


    【解决方案1】:

    将此类添加到您的项目中:

    public class Section
    {
      [XmlElement("question")]
      public List<Question> Questions {get; set;}
    
      public Section()
      {
         Questions = new List<Question>();
      }
    }
    

    像这样修改Form类:

    [XmlRoot("form")]       
    public class Form       
    {       
        [XmlElement("question")]       
        public List<Question> Questions { get; set; }  
    
        [XmlElement("section")]     
        public List<Section> Sections {get; set;}
    
        public Form()       
        {       
              Questions = new List<Question>();       
              Sections = new List<Section>();
        }       
    }   
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      相关资源
      最近更新 更多