迭代XML元素[n] childs

时间:2016-02-04 13:28:02

标签: c# xml linq

我正在尝试遍历列表并且无法设法执行此操作。

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

以上产生错误: 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包含3个元素。

我想到shipments[shipmentId]并绕过他的后代。 我怎么能做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以像这样迭代元素的子元素:

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

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