Jacob Regan
Jacob Regan

Reputation: 107

Add alias/prefix to existing XML namespace

How can I convert the following XML

<root xmlns:xyz="do/not/change" xmlns="add/alias">
   <name>Test</name>
   <xyz:id>100<xyz:id>
</root>

To

<abc:root xmlns:xyz="do/not/change" xmlns:abc="add/alias">
   <abc:name>Test</abc:name>
   <xyz:id>100<xyz:id>
</abc:root>

Using XDocument in C#

Effectively, I want to add an alias to the second namespace, and add the prefix to all elements that do not already have a prefix.

All the information I can find is how to remove or add a namespace, but nothing about how to add a prefix/alias.

Upvotes: 3

Views: 2433

Answers (1)

xanatos
xanatos

Reputation: 111950

It should be something like:

var xml = @"<root xmlns:xyz='do/not/change' xmlns='add/alias'>
   <name>Test</name>
   <xyz:id>100</xyz:id>
</root>";

var xdoc = XDocument.Parse(xml);

var xn = xdoc.Root.GetDefaultNamespace();
xdoc.Root.SetAttributeValue(XNamespace.Xmlns + "abc", xn.NamespaceName);
xdoc.Root.Attribute("xmlns").Remove();

foreach (var el in xdoc.Root.DescendantsAndSelf())
{
    if (el.Name.Namespace == xn)
    {
        el.Name = xn + el.Name.LocalName;
    }
}

Note that this code will break if there is no default namespace defined.

You can add a check like:

if (xn.NamespaceName == string.Empty) ...

Note 2: technically even attributes can have namespaces, like xyz:myattr="Hello". We are skipping this.

Upvotes: 5

Related Questions