如何初始化XmlElement []?

时间:2015-09-27 07:50:24

标签: wcf xmlserializer

我有一个自动生成的代理类,其中包含字段XmlElement[] Any。 在协议规范中,允许使用各种其他类型。 我该如何初始化这个字段?

例如,我可能有:

  Any = new XmlElement[1];
  Any[0] = new SomeRequestType().AsXmlElement()

我如何在代码中为AsXmlElement腾出空间?

public partial class AppDataType
{

    private System.Xml.XmlElement[] anyField;

    private System.Xml.XmlAttribute[] anyAttrField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAnyElementAttribute(Order=0)]
    public System.Xml.XmlElement[] Any
    {
        get
        {
            return this.anyField;
        }
        set
        {
            this.anyField = value;
        }
    }

1 个答案:

答案 0 :(得分:0)

要直接从XmlElement序列化,您可以使用:

public static class XmlNodeExtensions
{
    public static XmlDocument AsXmlDocument<T>(this T o, XmlSerializerNamespaces ns = null, XmlSerializer serializer = null)
    {
        XmlDocument doc = new XmlDocument();
        using (XmlWriter writer = doc.CreateNavigator().AppendChild())
            new XmlSerializer(o.GetType()).Serialize(writer, o, ns);
        return doc;
    }

    public static XmlElement AsXmlElement<T>(this T o, XmlSerializerNamespaces ns = null, XmlSerializer serializer = null)
    {
        return o.AsXmlDocument(ns, serializer).DocumentElement;
    }

    public static T Deserialize<T>(this XmlElement element, XmlSerializer serializer = null)
    {
        using (var reader = new ProperXmlNodeReader(element))
            return (T)(serializer ?? new XmlSerializer(typeof(T))).Deserialize(reader);
    }

    /// <summary>
    /// Return an XmlSerializerNamespaces that disables the default xmlns:xsi and xmlns:xsd lines.
    /// </summary>
    /// <returns></returns>
    public static XmlSerializerNamespaces NoStandardXmlNamespaces()
    {
        var ns = new XmlSerializerNamespaces();
        ns.Add("", ""); // Disable the xmlns:xsi and xmlns:xsd lines.
        return ns;
    }
}

public class ProperXmlNodeReader : XmlNodeReader
{
    // Bug fix from http://stackoverflow.com/questions/30102275/deserialize-object-property-with-stringreader-vs-xmlnodereader
    public ProperXmlNodeReader(XmlNode node)
        : base(node)
    {
    }

    public override string LookupNamespace(string prefix)
    {
        return NameTable.Add(base.LookupNamespace(prefix));
    }
}

然后使用它:

        var appDataType = new AppDataType
        {
            Any = new[] { someRequestType.AsXmlElement() },
        };

原型fiddle