Change 1:
If you add a namespace attribute to an element, this will force it to add a prefix. But you still get the xmlns attribute in node. To remove it, you probably need to use XmlWriter, as Jeff says.
Edit 2:
To get the EXACT XML you need, you also need to create a root element:
Edit 3:
OK. I found a way to get what you want without XmlWriter:
var xml = "<myPrefix:Catalog xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" xmlns:sys=\"clr-namespace:System;assembly=mscorlib\" xmlns:myPrefix=\"clr-namespace:........\"><myPrefix:Item Name=\"Item1\" Mode=\"All\" /></myPrefix:Catalog>"; XNamespace presentation = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"; XNamespace xaml = "http://schemas.microsoft.com/winfx/2006/xaml"; XNamespace mscorlib = "clr-namespace:System;assembly=mscorlib"; XNamespace myPrefix = "clr-namespace:......."; XElement container = XElement.Parse(xml); var xmlTree = new XElement("Item", new XAttribute("Name", "Item2"), new XAttribute("Mode", "Single")); container.Add(xmlTree); foreach (var el in container.DescendantsAndSelf()) { el.Name = myPrefix.GetName(el.Name.LocalName); var atList = el.Attributes().ToList(); el.Attributes().Remove(); foreach (var at in atList) { if (el.Name.LocalName == "Catalog" && at.Name.LocalName != "xmlns") continue; el.Add(new XAttribute(at.Name.LocalName, at.Value)); } } container.Add(new XAttribute(XNamespace.Xmlns + "x", xaml)); container.Add(new XAttribute(XNamespace.Xmlns + "sys", mscorlib)); container.Add(new XAttribute(XNamespace.Xmlns + "myPrefix", myPrefix));
Change 4:
Apparently there was an easier way ... LOTION is easier ... see Other answers.
Sani singh huttunen
source share