简体   繁体   English

部分定制XML序列化

[英]XML Serialization Customized Partially

in brief what I need is that to custom the class project partially 简而言之,我需要的是部分自定义类项目

public class project : IXmlSerializable
{
    [XmlAttribute]
    public string name;
    [XmlIgnore]
    public string[] contents;
    public XmlSchema GetSchema()
    {
        return null;
    }

  public void ReadXml(XmlReader reader)
  {
      if (reader.HasAttributes)
      {
          contents=new string[reader.AttributeCount];
          for (int i = 0; i < reader.AttributeCount; i++)
          {
              reader.MoveToAttribute(i);
              string attr = reader.Name;
              Regex reg = new Regex(@"content_\d+");
              if (reg.IsMatch(attr))
              {
                  contents[i] = reader.Value;
              }
          }
      }
  }

  public void WriteXml(XmlWriter writer)
  {
      for (int i = 0; i < contents.Count(); i++)
      {
          writer.WriteAttributeString("content_" + i, contents[i]);
      }
  }
}

I want name to be serialized normally but custom only the contents of the array (I need to make it as attribute in project node ). 我希望名称可以正常序列化,但仅自定义数组的内容(我需要将其作为项目节点中的属性)。 what happen actually is when I implement the project class the name is kept null any idea how can I do this? 实际上,当我实现项目类时,名称保持为空,怎么办呢?

In ReadXml method you never assign name property. ReadXml方法中,您永远不会分配name属性。 Just add 只需添加

name= "someValue";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM