Insert XElements using LINQ Select?

I have a source xml chunk where I want to insert multiple elements that are generated depending on certain values ​​found in the source xml

I currently have a sub that does this for me:

<Extension()>
Public Sub AddElements(ByVal xml As XElement, ByVal elementList As IEnumerable(Of XElement))

    For Each e In elementList
        xml.Add(e)
    Next

End Sub

      

And it is called in the routine like this:

Dim myElement = New XElement("NewElements")

myElement.AddElements(
     xml.Descendants("TheElements").
     Where(Function(e) e.Attribute("FilterElement") IsNot Nothing).
     Select(Function(e) New XElement("NewElement", New XAttribute("Text", e.Attribute("FilterElement").Value))))

      

Is it possible to overwrite it with Linq syntax so I don't need to call Sub AddElements, but can do it all in mode

Many thanks

Simon

+2


a source to share


1 answer


Sure:

Dim outputxml = 
   New XElement("NewElements",
      xml.Descendants("TheElements").
      Where(Function(e) e.Attribute("FilterElement") IsNot Nothing).
      Select(Function(e) _
         New XElement("NewElement", 
            New XAttribute("Text",e.Attribute("FilterElement").Value)
         )
      )
   )

      

XElement

and XAttribute

have constructors that (in addition to the element or attribute name) accept an arbitrary number of objects (which can themselves be queries or others IEnumerables

). Anything you pass to the constructor is added as content.

You can also look at XML literals, which make this more readable, but essentially do the same thing.



With XML Literals, it looks like this:

dim outputxml = 
   <NewElements><%=   
      From e In xml...<TheElements> 
      Where e.@FilterElement IsNot Nothing 
      Select <NewElement Text=<%= e.@FilterElement %>/>
   %></NewElements>
' you can embed names and attribute values too

      

  • <%=

    %>

    adds VB expression value to XML
  • xml...<elemname>

    selects xml descendants called elemname
  • 'elem. @ attrname` gets the value of an attribute

It's almost XQuery; -).

+2


a source







All Articles