I'm looking for the XmlSerializer functionality to re-create some namespace/type info in my output XML.
So I have to replicate XML output like this to an old COM application:
<Amount dt:dt="int">500</Amount>
<StartTime dt:dt="dateTime">2014-12-30T12:00:00.000</StartTime>
I currently set the attributes of my properties like so:
[XmlElement(ElementName = "Amount", Namespace = "urn:schemas-microsoft-com:datatypes",
DataType = "int", Type = typeof(int))]
public int Amount{ get; set; }
With my XmlSerializer and Namespaces set like this:
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add("dt", "urn:schemas-microsoft-com:datatypes");
s.Serialize(writer, group, namespaces);
But this only gives me output like:
<dt:Amount>500</dt:Amount>
Anyone have an idea where I'm going wrong?
The
XmlElementAttribute.Namespace
specifies the namespace of the element itself, not an attribute of the element. That's why you are seeing thedt:
prefix. And theDataType = "int"
isn't helping you here; it's for specifying the type of polymorphic fields, and won't auto-generate adt
data type attribute. In fact, there's no built-in functionality inXmlSerializer
to auto-generate an XDR data type attribute values, which belong in the namespace"urn:schemas-microsoft-com:datatypes"
.Thus, it's necessary to do it manually, using a wrapper struct with the necessary attribute. The following implementation is typed rather than polymorphic:
Then use it in your classes with proxy properties as follows:
Which produces the following XML:
Prototype fiddle.