0

I am trying to get all descendant XElements including root element of an XElement according to presence of specific attribute. My not very nice attempt:

var myXElements = form.FormData.Descendants().Where(e => e.Attributes().Where(a => a.Name == myProperty).Count() > 0).ToList();
// Extra for root element
if (form.FormData.Attribute(myProperty) != null)
{
    myXElements.Add(form.FormData);
}

where form.FormData is XElement type (I recive it from .dll) and myProperty is the specific property.

Is there more elegent way to achive this?

  • You do not need to get all the descendants. Getting the parent automatically gets the entire tree. – jdweng Dec 07 '20 at 11:03
  • @jdweng Please demonstrate how that would help to reduce the starting XML `` to a list of two XElements `{ , }`. – GSerg Dec 07 '20 at 12:39
  • What is needed is the root element in following : form.FormData.D.Descendants("Element Name") – jdweng Dec 07 '20 at 13:26
  • @jdweng That will give you a list of all elements that have the tag name of "Element name". The OP wants a list of descendant elements, regardless of their name, that have a certain attribute on them. – GSerg Dec 07 '20 at 13:38
  • @GSerg : The XElement will include the descendants. – jdweng Dec 07 '20 at 13:52
  • @jdweng There is no *the* XElement, `Descendants("Element Name")` returns a sequence of all descendant XElements that have the name of "Element Name". Some of these elements do not have the attribute on them, they must not be returned, but they will. Some of the other XElements that do have the attribute on them will be missed because they were children of other elements, not named "Element Name". Have you actually read the question? – GSerg Dec 07 '20 at 13:55
  • @GSerg : There is if the root is form.FormData. – jdweng Dec 07 '20 at 14:18

1 Answers1

-2
var myXElements = form.FormData.DescendantsAndSelf().Where(e => e.Attribute(myProperty) != null).ToList()
GSerg
  • 76,472
  • 17
  • 159
  • 346
  • Although this code might solve the problem, a good answer should explain **what** the code does and **how** it helps. – BDL Dec 07 '20 at 12:53
  • 1
    @BDL That's exactly what I wanted. Also I don't agree with -1 for you becouse answer is just little tweek and simplification of my attempt. Thanks m8! – Ondřej Kašpar Dec 08 '20 at 11:29
  • @OndřejKašpar: I didn't vote on the answer. The comment was posted from inside the low quality review queue. In general, answers with out explanation are suboptimal for everyone except the asker because you have to compare what the code actually changed. A short sentence stating what has been changed and why improves answers a lot. – BDL Dec 08 '20 at 13:17
  • @BDL Ok, I didn't know that. Thank you for explanation! – Ondřej Kašpar Dec 09 '20 at 05:50