0
[XmlRoot("company"), DataContract(Name = "company")]
public class Company : IProvideSerialization
{
    /// <summary>
    /// Stock exchange the company is in.
    /// </summary>
    /// <see cref="https://developer.linkedin.com/documents/company-lookup-api-and-fields"/>
    /// <remarks>Available only for public companies.</remarks>
    [XmlElement("stock-exchange"), DataMember(Name = "stock-exchange", EmitDefaultValue = false, IsRequired = false), EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
    protected SerializableEnum<StockExchange> StockExchangeForXML;
    public static Company FromXml(String XML)
    {
        XmlSerializer x = new XmlSerializer(typeof(Company));
        return (Company)x.Deserialize(new StringReader(XML));
    }
}

SerializableEnum 实现 IXmlSerializable。

SerializableEnum 也有一个有效的 FromXml;它看起来如下:

    public static SerializableEnum<T> FromXml(string XML)
    {
        XmlRootAttribute XR = (XmlRootAttribute)System.Attribute.GetCustomAttribute(typeof(T), typeof(XmlRootAttribute));
        XmlSerializer x = new XmlSerializer(typeof(SerializableEnum<T>), new XmlRootAttribute() { ElementName = XR.ElementName, IsNullable = true });
        return (SerializableEnum<T>)x.Deserialize(new StringReader(XML));
    }

当我做:

        String StockXML = "<stock-exchange><code>NMS</code><name>NASDAQ</name></stock-exchange>";
        String CompanyXML = "<company><stock-exchange><code>NMS</code><name>NASDAQ</name></stock-exchange></company>";

        SerializableEnum<StockExchange> Stock = SerializableEnum<StockExchange>.FromXml(StockXML);
        Company Cmp = Company.FromXml(CompanyXML);

Stock 将填充数据,但 Cmp 不会填充 Stock 数据(看起来 ReadXml 永远不会被调用)......

我尝试向 XmlSerializer 添加其他类型(例如,new Type[] {typeof(SerializableEnum)}),但这无济于事。

我在这里想念什么?谢谢。

我认为它可能类似于我必须在 SerializableEnum 类的 FromXml 中添加的 RootElementAttribute。IXmlSerializable 忽略了枚举具有的 XmlRoot 属性,因此我添加了该代码以在反序列化时添加它。有没有不同的方法可以让这一切一起工作?

4

1 回答 1

2

我认为 Company 类没有实现IXmlSerializable。

默认 Xml 序列化忽略所有非公共和只读成员,因此它忽略protected StockExchangeForXML.

于 2012-07-12T16:24:25.807 回答