Eran Meir
Eran Meir

Reputation: 983

Iterate through XML element[n] childs

I am trying to iterate through a list and can't manage to do it.

  public void SetShipmentsIndex(int shipmentId, string sourceShipmentIndex, IEnumerable<XElement> shipments)
  {
        var currentShipment = shipments.ToList()[shipmentId];

        foreach (var el in currentShipment)
        {
            if (el.Name == "sourceShipmentId")
            {
                el.SetValue(sourceShipmentIndex);
            }

            if (el.Name == "shipmentIndex")
            {
                el.SetValue(shipmentId);
            }
        }
    }

above produce an error: foreach statement cannot operate on variables of type 'System.Xml.Linq.XElement' because 'System.Xml.Linq.XElement' does not contain a public definition for 'GetEnumerator'

shipments contains 3 elements.

i am trying to get to shipments[shipmentId] and loop though his descendants. How can i accomplish that?

Upvotes: 0

Views: 78

Answers (1)

chameleon
chameleon

Reputation: 1004

You can iterate through the childs of the element like this:

foreach (var el in currentShipment.Elements())
    {
        if (el.Name == "sourceShipmentId")
        {
            el.SetValue(sourceShipmentIndex);
        }

        if (el.Name == "shipmentIndex")
        {
            el.SetValue(shipmentId);
        }
    }

Upvotes: 1

Related Questions