【问题标题】:Specifing more than 1 XmlRoot attribute指定超过 1 个 XmlRoot 属性
【发布时间】:2018-01-18 10:56:13
【问题描述】:

我有一个类用于存储反序列化的 XML 数据。我想让这个类向后兼容,以便它接受旧的 Root 元素名称。

<XmlRoot(ElementName:="cancellation-response")>
Public Class ApplicantResponse
    ' properties go here!
End Class

如果根元素是“applicant-response”“cancellation-response”,我希望反序列化程序使用此类。

<XmlRoot(ElementName:="applicant-response")>
<XmlRoot(ElementName:="cancellation-response")>
Public Class ApplicantResponse
    ' properties go here!
End Class

这可能吗?

当前 Visual Studio 使用上述方法报错:

属性“XmlRootAttribute”不能多次应用。

谢谢。

【问题讨论】:

  • 您需要将设置更改为 Fragment : XmlWriterSettings settings = new XmlWriterSettings(); settings.ConformanceLevel = ConformanceLevel.Fragment; XmlWriter writer = XmlWriter.Create("filename",settings);

标签: xml vb.net deserialization


【解决方案1】:

我的解决方案是将根名称动态传递到 XmlSerializer:

xmlRoot = New XmlRootAttribute(myRootName)  
serializer = New XmlSerializer(GetType(ApplicantResponse), xmlRoot) 
response = CType(serializer.DeSerialize(New StringReader(serializedResponse)), ApplicantResponse)

其中 myRootName 是“applicant-response”或“cancellation-response”。

【讨论】:

  • 这是正确的。您不能同时指定多个根元素名称,因为有效的 XML 文档只能有一个根元素。干得好!
  • 谢谢!刚刚更新了直接使用 XmlSerializer 而不是我的帮助库的答案。现在,如果我需要恢复到以前的版本,我只需将 myRootName 作为数据库值或应用设置的一部分进行更改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-02
  • 1970-01-01
  • 2015-03-15
  • 2015-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多