0
我正在使用XMLIgnore屬性在序列化中刪除不需要的屬性。但我想只從子類中刪除一些基類屬性。我想要基類的屬性,但它不應該在子類節點中重複。XMLIgnore:從子類節點中刪除基類屬性
是否可以從子類節點中刪除基類屬性?
在我的代碼中,我得到的輸出格式如下:當我通過XMLIgnore從基類中刪除屬性。
<?xml version="1.0" encoding="utf-8"?>
<InformationCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<projects>
<Project xsi:type="Group">
<GroupName>Accounts</GroupName>
<Comment>Financial Transaction</Comment>
</Project>
</projects>
</InformationCollection>
但下面格式實際上我期待輸出
<?xml version="1.0" encoding="utf-8"?>
<InformationCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<projects>
<ProjectId>1</ProjectId>
<ProjectName>HRMS</ProjectName>
<Project xsi:type="Group">
<GroupName>Accounts</GroupName>
<Comment>Financial Transaction</Comment>
</Project>
</projects>
</InformationCollection>
我試圖這樣下面的代碼:
[XmlInclude(typeof(Group))]
public class Project
{
public int ProjectId { get; set; }
public string ProjectName { get; set; }
public Project() { }
public Project(int projectId, string projectName)
{
ProjectId = projectId;
ProjectName = projectName;
}
}
public class Group : Project
{
public string GroupName;
public string Comment;
public Group():base() { }
public Group(int projectId, string projectName)
: base(projectId, projectName)
{
}
public Group(int projectId, string projectName, string groupName, string comment)
: this(projectId, projectName)
{
GroupName = groupName;
Comment = comment;
}
}
public class InformationCollection
{
public List<Project> projects = new List<Project>();
public InformationCollection()
{
projects.Add(new Group(1,"HRMS","Accounts","Financial Transaction"));
}
}
class Program
{
static void Main(string[] args)
{
SerializeObject("IgnoreXml.xml");
}
public static XmlSerializer CreateOverrider()
{
XmlAttributeOverrides xOver = new XmlAttributeOverrides();
XmlAttributes attrs = new XmlAttributes();
attrs.XmlIgnore = true;
xOver.Add(typeof(Project), "ProjectName", attrs);
xOver.Add(typeof(Project), "ProjectId", attrs);
XmlSerializer xSer = new XmlSerializer(typeof(InformationCollection), xOver);
return xSer;
}
public static void SerializeObject(string filename)
{
try
{
XmlSerializer xSer = CreateOverrider();
InformationCollection informationCollection = new InformationCollection();
TextWriter writer = new StreamWriter(filename);
xSer.Serialize(writer, informationCollection);
writer.Close();
}
catch (Exception ex)
{
throw;
}
}
}