C# 是否可以将xml中的字符串值强制为bool?
假设我有这样的xml:C# 是否可以将xml中的字符串值强制为bool?,c#,xml-serialization,coercion,C#,Xml Serialization,Coercion,假设我有这样的xml: <Server Active="No"> <Url>http://some.url</Url> </Server> 是否可以将活动属性更改为类型bool,并让XmlSerializer强制将“是”或“否”更改为bool值 编辑:收到Xml,我无法更改它。因此,事实上,我只对反序列化感兴趣。是的,您可以实现,并且可以控制xml的序列化和反序列化方式 public class Server { [XmlAttri
<Server Active="No">
<Url>http://some.url</Url>
</Server>
是否可以将活动属性更改为类型bool
,并让XmlSerializer强制将“是”或“否”更改为bool值
编辑:收到Xml,我无法更改它。因此,事实上,我只对反序列化感兴趣。是的,您可以实现,并且可以控制xml的序列化和反序列化方式
public class Server
{
[XmlAttribute()]
public bool Active { get; set; }
public string Url { get; set; }
}
前一个类应以该序列化形式结束:
<Server Active="false">
<Url>http://some.url</Url>
</Server>
http://some.url
我可以看看第二个属性:
[XmlIgnore]
public bool Active { get; set; }
[XmlAttribute("Active"), Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public string ActiveString {
get { return Active ? "Yes" : "No"; }
set {
switch(value) {
case "Yes": Active = true; break;
case "No": Active = false; break;
default: throw new ArgumentOutOfRangeException();
}
}
}
然而,在一般情况下(如果我们假设存在嵌套对象等),这是一个必须实现的非常可怕的接口。我唯一的抱怨是ActiveString将在同一个项目中的IntelliSense中可见。@Kugel-在同一个项目中,是的。
[EditorBrowsable(…)]
至少尝试处理其他项目,但……这与OP要求的内容不匹配(他无法更改xml)?
[XmlIgnore]
public bool Active { get; set; }
[XmlAttribute("Active"), Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public string ActiveString {
get { return Active ? "Yes" : "No"; }
set {
switch(value) {
case "Yes": Active = true; break;
case "No": Active = false; break;
default: throw new ArgumentOutOfRangeException();
}
}
}