Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding xml:space to root element

I have a little problem that I thought was a no-brainer ... but alas ...

I have some xml and all I want to do is to add the xml:space="preserve" to the root element using c#.

I tried this:

var rootElem = xDoc.Root; // XDocument
rootElem.SetAttributeValue("{xml}space", "preserve");

The result of this is:

<ProjectDetails xmlns="http://site/ppm" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" p3:space="preserve" xmlns:p3="xml">

I think this is equivalent to

<ProjectDetails xmlns="http://site/ppm" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xml:space="preserve">

But since xml:space is a special attribute, I am a bit in doubt.

So:

Are they identical?

Is there a way I can add this to the document in a "clean" way?

like image 918
Jesper Lund Stocholm Avatar asked Mar 07 '16 14:03

Jesper Lund Stocholm


1 Answers

You just need the right XName value - I'd use this:

doc.Root.SetAttributeValue(XNamespace.Xml + "space", "preserve");

The XName +(XNamespace, string) operator is generally the simplest way to work with namespaces in LINQ to XML, in my experience.

like image 56
Jon Skeet Avatar answered Sep 27 '22 16:09

Jon Skeet