2016-08-20 86 views
0

在过去的一天左右,我一直在将我的应用程序升级到.NET Core,netcoreapp1.0,从net451。大部分流程进行得非常顺利,我看到的所有事情都被移除了一个以上的问题。.NET核心中的未知属性的XML序列化

我正在使用System.XmlSystem.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的一部分了。我一直无法找到处理未知属性的另一种方法,并且希望能找到正确方向的指针。

+0

从文档[这里](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

+0

谢谢@dbc。我确实看到了,但是,当我尝试这个例子时,'XmlAttribute []'不是一个类型。不知道我是否错过了一个图书馆,或者是否有什么事情在我的最后被严重破坏。我有'XmlAttributeAttribute','XmlAttributes'和'XmlAttributeOverrides'。 'XmlAttribute'没有别的。任何想法?编辑:我也看到它在这里:https://docs.microsoft.com/en-us/dotnet/core/api/system.xml#System_Xml_XmlAttribute,但是,它不会编译时,当我尝试使用它。 – JasCav

+0

您可能需要:https://www.nuget.org/packages/System.Xml.XmlDocument/ – dbc

回答

2

而不是使用一个未知的属性时,您可以将public XmlAttribute[] XmlAttributes属性添加到您的PersonDetails,与[XmlAnyAttribute]标记它,并处理未知属性有:

public class PersonDetails 
{ 
    [XmlAttribute] 
    public string Address { get; set; } 

    [XmlAnyAttribute] 
    public XmlAttribute[] XmlAttributes 
    { 
     get 
     { 
      return null; 
     } 
     set 
     { 
      if (value != null) 
      { 
       foreach (var attr in value) 
        if (attr.Name == "Address_x0_") 
         Address = attr.Value; 
      } 
     } 
    } 
} 

当你发现,你将需要添加https://www.nuget.org/packages/System.Xml.XmlDocument/在.NET Core中使用XmlAttribute