簡體   English   中英

部分定制XML序列化

[英]XML Serialization Customized 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]);
      }
  }
}

我希望名稱可以正常序列化,但僅自定義數組的內容(我需要將其作為項目節點中的屬性)。 實際上,當我實現項目類時,名稱保持為空,怎么辦呢?

ReadXml方法中,您永遠不會分配name屬性。 只需添加

name= "someValue";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM