XElement Iteration and adding it to parent

hi I have the following question ...please do help as I am very new to programming in C# with no previous programming experience...

In my code I am suppose to Iterate through XElement in a Xml file add that Xelement to a parent known as Capability....This is my code...

if (xElem.HasElements)
        {

            foreach (XElement xChild in xElem.Element("Elements"))
            {
                Capability capChild = Parse(xChild);
                capParent.Children.Add(capChild);
            }
        }

here the foreach loop gives an error

Error 32 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'........

how can I carry out the functionality of finding if XElement has any child and adding it to the parent Capability?


First fix, add an 's' :

//foreach (XElement xChild in xElem.Element("Elements"))
  foreach (XElement xChild in xElem.Elements("Elements"))

This assumes that there are 1 or more tags <Elements> in your XML under xElem.


Henk's answer should work but I personally would use

    foreach (XElement xChild in xElem.Descendants())

where xElem would equal the parent element you want all child elements for. Or you could also use a LINQ query to basically accomplish the same task

    var children =
       from xChild in xElem.Descendants()
       select Parse(xChild)

which should return an IEnumerable that you can loop through and add that way.

EDIT:

It also just dawned on me that you said you're new to C# with no previous programming experience. I think it's also important that you understand WHY this error was thrown. In C# in order to use a foreach loop the collection must implement IEnumerable. This so that collection types can define how the data is enumerated. XElement is not enumerable because it's meant to represent a single element, not a collection of elements. So using xElem.Element("ElementName") is meant to return a single result, not an array or collection. Using xElem.Elements("ElementName") will return a collection of all the XElements that match the XName. However if you want all the child elements of a single element regardless of name this is where xElem.Descendants() comes in to play. Which one you use depends on what data you need and how your adding it.

链接地址: http://www.djcxy.com/p/53790.html

上一篇: IDictionaryEnumerator不是一个迭代器接口类型?

下一篇: XElement迭代并将其添加到父项