views:

89

answers:

2

In VB.NET I can easily embed strings into XML literals using <xml><%= "my string" %></xml>.

How can I embed an XElement instance?

I know I can use methods on the XElement, XNode, etc classes, but I'd like to do it in the XML literals if possible.

A: 

If you really need to do that, you could always just do this:

<xml><%= myXElement.ToString() %></xml>

I can't think of any example where you would want to do this though. Care to elaborate on why you need this? It would have to write out the XElement string, then parse it before adding it back into the object model (I imagine that's how it would have to work at least).

Ocelot20
I'm using XLinq and XML Literals to perform a transformation, much like what you would do with an XSLT. At the moment I have a block of XML literals that is about 200 lines long that performs the transformation. Attribute values and text are generated with `<%= myElement.ExtensionMethod() %>` blocks. I was hoping to break out some blocks of the XML literals into their own method and return an XElement that gets embedded back into the main block of XML literals.
GiddyUpHorsey
Your solution would work, but I'd rather not convert to string and then parse back into XElement. I was hoping there was a more natural way to do it.
GiddyUpHorsey
Instead of using all XML Literals, you could use a mix of the XDocument/XElement constructors and your literals to create the root document (think of how a C#-er would have to do it). That or add the XElements into your document via LINQ-to-XML to insert into specific target areas.
Ocelot20
+1  A: 

It turns I can simply do the following:

Function GetSomeMoreXml() As XElement
   Return <moreXml/>
End Function

Sub Main()
   Dim myXml = <myXml>
                  <%= GetSomeMoreXml() %>
               </myXml>
End Sub

Which is pretty neat. It allows me to break up my XML literals into more manageable chunks.

GiddyUpHorsey