C#将元素添加到集合

时间:2015-07-08 07:02:45

标签: c#

我试图将XmlElement添加到XmlElement [],但这似乎是不可能的。

错误消息:

  

无法隐式转换类型' System.Xml.XmlElement'至   ' System.Xml.XmlElement []'

     

XmlElement []对象没有添加或插入函数

所以我该怎么做?

使用代码进行更新:

此部分是从XSD创建的         private System.Xml.XmlElement [] anyField;

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

这里我尝试创建对象并将UniversalShipment添加到Any集合中。

    UniversalInterchangeBody body = new UniversalInterchangeBody();
    UniversalShipmentData shipmentData = new UniversalShipmentData();
    XmlElement universalShipmentXML = SerializeToXmlElement(shipmentData);
    body.Any = universalShipmentXML;

    public static XmlElement SerializeToXmlElement(object o)
    {
        XmlDocument doc = new XmlDocument();

        using (XmlWriter writer = doc.CreateNavigator().AppendChild())
        {
            new XmlSerializer(o.GetType()).Serialize(writer, o);
        }
        return doc.DocumentElement;
    }

3 个答案:

答案 0 :(得分:2)

我会使用List。

List<XmlElement> elements = new List<XmlElement>();
elements.Add(xamlElement);

答案 1 :(得分:0)

数组预先调整大小,并在数组的所有条目中使用默认元素。您无法通过插入/添加来重新调整数组的大小(如果您确实希望这样做,请使用FrameLayout infolayout; infolayout = (FrameLayout) findViewById(R.id.infoLayout); public void infoPressed(View v){//info button is pressed by user //infoLayout.setVisibility(View.GONE); infolayout.setVisibility(View.INVISIBLE); } <FrameLayout android:layout_width="193dp" android:layout_height="200dp" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignBottom="@+id/serviceLayout" android:id="@+id/infoLayout"> 代替)。否则,只需在特定索引处设置条目的值:

List<T>

答案 2 :(得分:0)

是的,它确实是Add XmlElement to XmlElement [] dynamically的副本,对不起!

在这种情况下我的代码的解决方案:

var uShipmentCollection = new UniversalShipmentData[]
{
    shipmentData
};

感谢您重复参考Gusdor!

相关问题