0

I'm trying to add an XmlElement to XmlElement[] but this seems to be impossible.

the errormessage:

Cannot implicitly convert type 'System.Xml.XmlElement' to 'System.Xml.XmlElement[]'

The XmlElement[] object does not have an Add or Insert function

so how can I do this?

Update with code:

This part is created from an XSD private System.Xml.XmlElement[] anyField;

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

Here I am trying to create the object and add a UniversalShipment to the Any collection.

    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;
    }
5
  • please share some code how you tried? Commented Jul 8, 2015 at 7:04
  • Can you post the code that generate this error ? Commented Jul 8, 2015 at 7:06
  • you have to add elements at indexes of the array. Commented Jul 8, 2015 at 7:07
  • already answered here: stackoverflow.com/questions/26125311/… Commented Jul 8, 2015 at 7:08
  • possible duplicate of Adding values to a C# array Commented Jul 8, 2015 at 7:09

3 Answers 3

2

I would use a List.

List<XmlElement> elements = new List<XmlElement>();
elements.Add(xamlElement);
Sign up to request clarification or add additional context in comments.

Comments

1

An array is pre-sized with default elements in all entries of the array. You cannot re-size the array by inserting/adding (if you do want to do this use a List<T> instead). Otherwise simply set the value of an entry at a specific index:

array[index] = value

Comments

0

Yes, it is indeed a copy of Add XmlElement to XmlElement [] dynamically sorry for this!

as for the solution to my code in this case:

var uShipmentCollection = new UniversalShipmentData[]
{
    shipmentData
};

Thanks for the duplicate reference Gusdor!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.