3

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.

1 Answer 1

5

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")
);
Sign up to request clarification or add additional context in comments.

1 Comment

Oh my... That was easy. Thanks also for the "single-creation" hint.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.