因为你提到了使用 XmlSerializer 来反序列化内容,
坚持下去,如果您已经为整个根对象创建了一个类,但又不想为 Rights 集合中的每个标志键入属性,这里还有一个使用 XmlSerializer.Deserialize() 的解决方案来帮助您。
[XmlRoot("root")]
public class RootObject
{
// . . . other properties
// . . . if you have them
// . . . and just don't put here anything
// . . . if you don't need them
public XmlElementDictionary<bool> Rights { get; set; }
}
如果您收到的 XML 格式与您在问题中输入的格式完全相同,则以下内容会将 Rights 元素解析为字典。通过实现 IXmlSerializable,我们告诉序列化系统我们想要自己序列化/反序列化这个类型。
请注意,未实现写入和架构支持。
public class XmlElementDictionary<TValue> : Dictionary<string, TValue>, IXmlSerializable
{
void IXmlSerializable.ReadXml(XmlReader reader)
{
string startElementName = reader.Name;
while (reader.Read())
{
string keyName = reader.Name;
if (keyName == startElementName) break;
reader.Read(); // Read element value
base.Add(keyName, (TValue)Convert.ChangeType(reader.Value, typeof(TValue)));
reader.Read(); // Read end element
}
}
System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema() { throw new NotImplementedException(); }
void IXmlSerializable.WriteXml(XmlWriter writer) { throw new NotImplementedException(); }
}
泛型实现使其可重用于其他类型。可以改进读取逻辑以检查任何属性(如果有属性现在会失败,但应该让您清楚地了解如何仅读取元素及其内部文本)
这里是如何使用它:
static void Main(string[] args)
{
RootObject rootObject =
(RootObject)new XmlSerializer
(typeof(RootObject)).Deserialize(new StringReader(XML));
if(rootObject.Rights["admin"])
{
. . . .
}
}