XmlIgnoreAttribute忽略属性的IsEnabled
和isEnabledFieldSpecified
,因为它们具有相似的名称。如何解决这个问题?作为i property secondCar
的结果,我有IsEnabled=false
,但我希望得到IsEnabled=true
。也许这是重复的问题,但我无法在堆栈上找到答案。
class Program
{
static void Main(string[] args)
{
Car firstCar = new Car() { IsEnabled = true };
Car secondCar = new Car() { IsEnabled = false };
secondCar = XmlUtility.XmlStr2Obj<Car>(XmlUtility.Obj2XmlStr(firstCar));
}
}
[Serializable]
public class Car
{
private bool isEnabledFieldSpecified;
private bool isEnabledField;
[XmlAttributeAttribute()]
public bool IsEnabled
{
get
{
return this.isEnabledField;
}
set
{
this.isEnabledField = value;
}
}
[XmlIgnoreAttribute()]
public bool IsEnabledSpecified
{
get
{
return this.isEnabledFieldSpecified;
}
set
{
this.isEnabledFieldSpecified = value;
}
}
}
namespace Utils
{
public class XmlUtility
{
public static string Obj2XmlStr(object obj, string nameSpace)
{
if (obj == null) return string.Empty;
XmlSerializer sr = SerializerCache.GetSerializer(obj.GetType());
StringBuilder sb = new StringBuilder();
StringWriter w = new StringWriter(sb, CultureInfo.InvariantCulture);
sr.Serialize(
w,
obj,
new XmlSerializerNamespaces(
new[]
{
new XmlQualifiedName("", nameSpace)
}
));
return sb.ToString();
}
public static string Obj2XmlStr(object obj)
{
if (obj == null) return string.Empty;
XmlSerializer sr = SerializerCache.GetSerializer(obj.GetType());
StringBuilder sb = new StringBuilder();
StringWriter w = new StringWriter(sb, CultureInfo.InvariantCulture);
sr.Serialize(
w,
obj,
new XmlSerializerNamespaces(new[] { new XmlQualifiedName(string.Empty) }));
return sb.ToString();
}
public static T XmlStr2Obj<T>(string xml)
{
if (xml == null) return default(T);
if (xml == string.Empty) return (T)Activator.CreateInstance(typeof(T));
StringReader reader = new StringReader(xml);
XmlSerializer sr = SerializerCache.GetSerializer(typeof(T));
return (T)sr.Deserialize(reader);
}
public static XmlElement XmlStr2XmlDom(string xml)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
return doc.DocumentElement;
}
public static XmlElement Obj2XmlDom(object obj, string nameSpace)
{
return XmlStr2XmlDom(Obj2XmlStr(obj, nameSpace));
}
}
internal class SerializerCache
{
private static readonly Hashtable Hash = new Hashtable();
public static XmlSerializer GetSerializer(Type type)
{
XmlSerializer res;
lock (Hash)
{
res = Hash[type.FullName] as XmlSerializer;
if (res == null)
{
res = new XmlSerializer(type);
Hash[type.FullName] = res;
}
}
return res;
}
}
}
答案 0 :(得分:-1)
尝试在两个对象中将IsEnabledSpecified属性设置为true。像这样:
Car firstCar = new Car() { IsEnabled = true, IsEnabledSpecified = true };
Car secondCar = new Car() { IsEnabled = false, IsEnabledSpecified = true };
这种方式序列化器会知道,应该序列化isEnabled属性。 IsEnabledSpecified属性对序列化程序有特殊意义:它本身不会被序列化(因为XmlIgnore属性),但它控制与xml元素相关的xml元素是否在xml有效负载中出现(“Specified”属性设置为true)(“指定的“属性设置为false”。