I have an element that inherits from XTypedElement (generated with LinqToXsd). It has a string property defined like this:
public string lang {
get {
XAttribute x = this.Attribute(XName.Get("lang", "xml"));
return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype);
}
set {
this.SetAttribute(XName.Get("lang", "xml"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype);
}
}
Originally it was generated with XName.Get(“lang”), but I added the namespace “XML” because the output should look like:
<tag xml:lang="nl-NL">...</tag>
instead, I now get this:
<tag p1:lang="nl-NL" xmlns:p1="xml">...</tag>
The following might be totally unrelated, but I know how to solve this problem using the old school System.Xml.Serialization.XmlSerializer class. There you can specify some namespaces when calling the Serialize method. The XTypedElement’s ToString() does not have an overload where I can specify such namespaces. Ideas anyone?
Answering my own question: after googeling a little more, I found this (and it did the trick):
I did wonder what that was returning (there’s only one overload and it’s a string) so I put a breakpoint on it and read the value of XNamespace.Xml.NamespaceName. it was “http://www.w3.org/XML/1998/namespace”. Somehow Linq-to-xml seems to know how that relates to “xml” 🙂
The correctly working code now looks like this: