Create xml attribute with namespace programatically

How can I create the following as XElement?

<data name="MyKey" xml:space="preserve">
    <value>Date of birth</value>
    <comment>Some comment</comment>
</data>

It throws

"The ':' character, hexadecimal value 0x3A, cannot be included in a name."

var data = new XElement("data");

data.Add(new XAttribute("name", translation.Key));
data.Add(new XAttribute("xml:space", "preserve")); // <-- here is the error

data.Add(new XElement("value") { Value = "Date of birth" });
data.Add(new XElement("comment") { Value = "Some comment" });

As this is part of a ResX-file, there will be many such <data></data>-elements.

Jon Skeet
people
quotationmark

Separate the namespace from the local name, using the XName +(XNamespace, string) operator for convenience:

data.Add(new XAttribute(XNamespace.Xml + "space", "preserve"));

Note that you can write the whole of your element creation in a single go rather more simply:

var data = new XElement("data",
    new XAttribute("name", "MyKey"),
    new XAttribute(XNamespace.Xml + "space", "preserve"),
    new XElement("value", "Date of birth"),
    new XElement("comment", "Some comment")
);

people

See more on this question at Stackoverflow