XElement Iteration and adding it to parent

主宰稳场 提交于 2019-12-10 17:07:12

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/13290108/xelement-iteration-and-adding-it-to-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!