使用XmlSerializer序列化对象时,如何将对象父类的属性也序列化成xml中的元素?
在下面的代码里,希望将carid和name序列化成xml元素usingSystem;usingSystem.Collections.Generic;usingSystem...
在下面的代码里,希望将carid和name序列化成xml元素
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
namespace SerializationDemo
{
class Program
{
static void Main(string[] args)
{
JamesBondCar jCar = new JamesBondCar(20, "james", "james description", false);
XmlSerializer xmlFormatter = new XmlSerializer(
typeof(JamesBondCar), //根节点
new Type[] { typeof(Car)}//子节点要用到的类
);
using (Stream fSteam = new FileStream("user.xml", FileMode.Create, FileAccess.Write, FileShare.None))
{
xmlFormatter.Serialize(fSteam, jCar);
}
Console.ReadLine();
}
}
public class Car
{
private uint _carId;
public uint CarId
{
get { return _carId; }
}
private string _name;
public string Name
{
get { return _name; }
}
public Car(uint carid, string name)
{
this._carId = carid;
this._name = name;
}
public Car()
{
}
}
[Serializable,
XmlRoot(Namespace = "http://www.abc.com")]
public class JamesBondCar : Car
{
private string _description;
[XmlElementAttribute(IsNullable = false)]
public string Description
{
get { return _description; }
set { _description = value; }
}
private bool _isNew;
[XmlAttribute]
public bool IsNew
{
get { return _isNew; }
set { _isNew = value; }
}
public JamesBondCar(uint carId, string name, string description, bool isNew)
: base(carId, name)
{
this._description = description;
this._isNew = isNew;
}
public JamesBondCar()
{
}
}
} 展开
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
namespace SerializationDemo
{
class Program
{
static void Main(string[] args)
{
JamesBondCar jCar = new JamesBondCar(20, "james", "james description", false);
XmlSerializer xmlFormatter = new XmlSerializer(
typeof(JamesBondCar), //根节点
new Type[] { typeof(Car)}//子节点要用到的类
);
using (Stream fSteam = new FileStream("user.xml", FileMode.Create, FileAccess.Write, FileShare.None))
{
xmlFormatter.Serialize(fSteam, jCar);
}
Console.ReadLine();
}
}
public class Car
{
private uint _carId;
public uint CarId
{
get { return _carId; }
}
private string _name;
public string Name
{
get { return _name; }
}
public Car(uint carid, string name)
{
this._carId = carid;
this._name = name;
}
public Car()
{
}
}
[Serializable,
XmlRoot(Namespace = "http://www.abc.com")]
public class JamesBondCar : Car
{
private string _description;
[XmlElementAttribute(IsNullable = false)]
public string Description
{
get { return _description; }
set { _description = value; }
}
private bool _isNew;
[XmlAttribute]
public bool IsNew
{
get { return _isNew; }
set { _isNew = value; }
}
public JamesBondCar(uint carId, string name, string description, bool isNew)
: base(carId, name)
{
this._description = description;
this._isNew = isNew;
}
public JamesBondCar()
{
}
}
} 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询