0
使用XmlSerializer類來序列化繼承基類「BaseClass」的派生類「MyContext」。 Base類屬性「attr1」,「attr2」不在序列化的XML輸出中。我需要Context類中的這些屬性和Context類中的嵌套類。請幫助這裏錯過什麼。Xml序列化基類屬性
namespace MyConsoleApplication
{
[System.Xml.Serialization.XmlIncludeAttribute(typeof(MyContextType))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class BaseType
{
private MyEnumType attr1Field;
private MyEnumType attr2Field;
[System.Xml.Serialization.XmlAttributeAttribute()]
public MyEnumType Attr1
{
get
{
return this.attr1Field;
}
set
{
this.attr1Field= value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public MyEnumType Attr2
{
get
{
return this.attr2Field;
}
set
{
this.attr2Field= value;
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlRootAttribute("Context", Namespace = "", IsNullable = false)]
public partial class MyContextType : BaseType
{
private string element1Field;
private string element2Field;
[System.Xml.Serialization.XmlElementAttribute(Order = 0)]
public string Element1
{
get
{
return this.element1Field;
}
set
{
this.element1Field = value;
}
}
[System.Xml.Serialization.XmlElementAttribute(Order = 1)]
public string Element2
{
get
{
return this.element2Field;
}
set
{
this.element2Field = value;
}
}
}
public enum MyEnumType
{
/// <remarks/>
False,
/// <remarks/>
True,
}
}
我串行代碼:
var mydoc = new XmlDocument();
var context = new MyContextType() { Element1 = "Car", Element2 = "Bike", Attr1 = "id1", Attr2 = "id2" };
using (MemoryStream stream = new MemoryStream())
{
XmlSerializer s = new XmlSerializer(typeof(MyContextType));
s.Serialize(XmlWriter.Create(stream), context);
stream.Flush();
stream.Seek(0, SeekOrigin.Begin);
mydoc.Load(stream);
}
輸出XML:
<MyContext>
<Element1>Happy</Element1>
<Element2>10</Element2>
</MyContext>
但我想輸出作爲
<MyContext attr1 = "False" attr2="False">
<Element1>Happy</Element1>
<Element2>10</Element2>
</MyContext>
'XmlSerializer'只會序列化公共類和成員。因爲它是你的'MyContext'類不能被序列化。你能提供一個[完整的例子](https://stackoverflow.com/help/mcve)你的問題嗎? – dbc
你的代碼不能編譯,你的類和屬性不公開。一旦我對這些問題做出合理的修復,我無法重現您的問題。請參閱https://dotnetfiddle.net/ueui7z – dbc
dbc:根據請求更新了代碼示例。請檢查並讓我知道 – KKR