如何初始化 XmlElement[]? [英] How to initialize XmlElement[]?

查看:31
本文介绍了如何初始化 XmlElement[]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an auto generated proxy class which contains field XmlElement[] Any. In the protocol specification a variety of other types are allowed. How would I initialize this field?

例如,我可能有类似的东西:

I might have, for example, something like:

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

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

How would I make room for AsXmlElement in my code?

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;
        }
    }

推荐答案

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

To serialize directly from and to an XmlElement, you can use:

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.

这篇关于如何初始化 XmlElement[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆