views:

170

answers:

1

I have an XElement that I need to create via dynamic xml literals/embedded expressions and I need it to inherit the default namespace. This doesn't appear possible though through everything I've tried. Does anyone know how to make this work?

For example

Imports <xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&gt;
Sub CreateXAML()
        Dim obj = "Rectangle"
        Dim objFill As String = obj & ".Fill"
        Dim myXML As XElement = <<%= obj %>><<%= objFill %>>no namespace</></>

        Dim myXML2 As XElement = <Path><Path.Fill>inherits namespace</Path.Fill></Path>
        MsgBox(myXML.ToString & vbCrLf & myXML2.ToString)
End Sub

The first one, myXML, is not created with the default ns, but the second one, myXML2, is.

+3  A: 

This is documented http://msdn.microsoft.com/en-us/library/bb675177.aspx in the Global Namespaces and Embedded Expressions section that it won't work, but the article doesn't provide a workaround or solution. I had this need before too and just through trial and error, was able to get it to work by creating the element in advance with the namespace in tow, like this:

Imports <xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&gt;
Sub CreateXAML()
    Dim shape = "Rectangle"
    Dim obj = <<%= "{http://schemas.microsoft.com/winfx/2006/xaml/presentation}" & shape %>></>
    Dim objFill = <<%= "{http://schemas.microsoft.com/winfx/2006/xaml/presentation}" & shape %>></>
    Dim myXML As XElement = <<%= obj %>><<%= objFill %>>has namespace</></>

    Dim myXML2 As XElement = <Rectangle><Rectangle.Fill>inherits namespace</Rectangle.Fill></Rectangle>
    MsgBox(myXML.ToString & vbCrLf & myXML2.ToString)
End Sub

You may wonder why the "Imports" statement is still there. Well, it is used in the case of adding in a non-dynamic XElement to inherit the global namespace. Like this:

<<%= obj %>><<%= objFill %>><Text>has namespace</Text></></>
Alison
This is brilliant. I had not been able to find a way to get the xmlns in there without a run time error, like *Dim obj = <<%= shape %> xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"></>*. Great, great, great!
Otaku
I just can't get over how great this is. It has cut my code by 50%!
Otaku