XElement Iterate and add it to the parent

Hi, I have the following question ... please help, as I am very new to C # programming without previous programming experience ...

In my code, I assume that Iterate through XElement in the Xml file will add Xelement to the 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 of the foreach statement cannot work with variables like "System.Xml.Linq.XElement" because "System.Xml.Linq.XElement" does not contain a public definition for "GetEnumerator" ........

how can I perform search functionality if an XElement has any child and adds it to the parent ability?

+4
source share
2 answers

First fix, add 's':

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

This assumes that your XML under xElem has 1 or more <Elements> tags.

+4
source

Henk's answer should work, but I personally used

  foreach (XElement xChild in xElem.Descendants()) 

where xElem will be equal to the parent for which you want all the children. Or you can also use the LINQ query to accomplish the same task.

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

which should return an IEnumerable, which you can skip and add in this way.

EDIT:

It also became clear to me that you said you were new to C # without programming experience. I think it is also important that you understand why this error was thrown. In C #, to use a foreach loop, a collection must implement IEnumerable. This means that collection types can determine how data is listed. XElement is not enumerable because it means representing a single element, not a collection of elements. Therefore, the use of xElem.Element ("ElementName") is intended to return a single result, not an array or collection. Using xElem.Elements ("ElementName") will return a collection of all XElements that match the XName. However, if you want all the children of the same element regardless of the name, xElem.Descendants () is used here. Which one you use depends on what data you need and how to add it.

+2
source

Source: https://habr.com/ru/post/1444805/


All Articles