What is the easiest way to change the namespace value using LINQ to XML?

TL / DR: what is the easiest way to change the namespace value with LINQ to XML, say from xmlns:gcs="clr-namespace:NsOne;assembly=AsmOne"to xmlns:gcs="clr-namespace:NsTwo;assembly=AsmTwo"?

Why? because:

I serialized Xamlusing System.Windows.Markup.XamlWriter.Save(myControl). I want to visualize this GUI look in another place (deserialization using System.Windows.Markup.XamlReader.Parse(raw)), in another project.

I do not want to reference the original assembly!

I just need to change the namespace, so XamlReader.Parse(raw)it will not throw an exception. I am currently using regular expressions and it works , but I don't like this method (for example, if I have one xmlns:gcs="clr-namespace:NsOne;assembly=AsmOne"inside CDATA)

This is my serialized Xaml:

<FlowDocument PagePadding="5,0,5,0" AllowDrop="True"
              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              xmlns:gcs="clr-namespace:NsOne;assembly=AsmOne"
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <gcs:MyParagraph Margin="0,0,0,0">
        <gcs:MyParagraph.MetaData>
            <gcs:ParagraphMetaData UpdaterParagraphUniqueId="1" />
        </gcs:MyParagraph.MetaData>
        <Span>some text...</Span>
    </gcs:MyParagraph>
    <gcs:MyParagraph Margin="0,0,0,0" Background="#FFF0F0F0">
        <gcs:MyParagraph.MetaData>
            <gcs:ParagraphMetaData UpdaterParagraphUniqueId="2" />
        </gcs:MyParagraph.MetaData>
        <Span Foreground="#FF0000FF">some more text...</Span>
    </gcs:MyParagraph>
</FlowDocument>

(MyParagraph ParagraphMetaData , . MyParagraph WPF Paragraph)

+4
1

.

var doc = XDocument.Parse(raw);
XNamespace fromNs = "clr-namespace:NsOne;assembly=AsmOne";
XNamespace toNs = "clr-namespace:NsTwo;assembly=AsmTwo";

// redefines "gcs", but doesn't change what namespace the elements are in
doc.Root.SetAttributeValue(XNamespace.Xmlns + "gcs", toNs);

// this actually changes the namespaces of the elements from the old to the new
foreach (var element in doc.Root.Descendants()
                                  .Where(x => x.Name.Namespace == fromNs))
    element.Name = toNs + element.Name.LocalName;

, XAML , xmlns XDocument. , "gcs", xmlns, . , , xmlns="clr-namespace:NsTwo;assembly=AsmTwo" gcs ( NsOne).

+6

All Articles