在过去的一天左右,我一直在将我的应用程序升级到.NET Core,netcoreapp1.0
,从net451
。大部分流程进行得非常顺利,我看到的所有事情都被移除了一个以上的问题。.NET核心中的未知属性的XML序列化
我正在使用System.Xml
和System.Xml.Serialization
来从API端点(我完全无法控制)序列化XML。它运行良好,但由于XML的问题,总是有一个属性返回为UnknownAttribute
。我处理它通过接线的事件是这样的:
XmlReader reader = XmlReader.Create(stream);
var serializer = new XmlSerializer(typeof(PersonDetails));
var personDetails = (PersonDetails)serializer.Deserialize(reader);
serializer.UnknownAttribute += new XmlAttributeEventHandler((object sender, XmlAttributeEventArgs e) => {
unknownAttr.Add(e.Attr.Name, e.Attr.Value);
});
// Handle the missing map value if it exists.
string addressValue;
if(unknownAttr.TryGetValue("Address_x0_", out addressValue))
{
personDetails.Address = addressValue;
}
通过升级到.NET的核心,我现在用的System.Xml.XmlSerializer 4.0.11库。现在,看起来UnknownAttribute事件不再是XmlSerializer
的一部分了。我一直无法找到处理未知属性的另一种方法,并且希望能找到正确方向的指针。
从文档[这里](https://docs.microsoft.com/en-us/dotnet/core/api/system.xml.serialization.xmlanyattributeattribute)看起来像dotnetcore仍然支持['XmlAnyAttributeAttribute']( https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlanyattributeattribute.aspx)。您可以沿着[如何用C#中的属性列表反序列化元素](https://stackoverflow.com/questions/32884364)中的行添加'[XmlAnyAttribute]'属性到'PersonDetails'类中,并查看为你的未知属性里面。 – dbc
谢谢@dbc。我确实看到了,但是,当我尝试这个例子时,'XmlAttribute []'不是一个类型。不知道我是否错过了一个图书馆,或者是否有什么事情在我的最后被严重破坏。我有'XmlAttributeAttribute','XmlAttributes'和'XmlAttributeOverrides'。 'XmlAttribute'没有别的。任何想法?编辑:我也看到它在这里:https://docs.microsoft.com/en-us/dotnet/core/api/system.xml#System_Xml_XmlAttribute,但是,它不会编译时,当我尝试使用它。 – JasCav
您可能需要:https://www.nuget.org/packages/System.Xml.XmlDocument/ – dbc