Suppose, I have a simple type:
public class Report
{
public Report()
{
BirthDate = new Element();
BirthPlace = new Element();
}
public Element BirthDate { get; set; }
public Element BirthPlace { get; set; }
}
public class Element
{
[XmlAttribute("published")]
public bool Published { get; set; }
[XmlText]
public string Value { get; set; }
}
I defined simple extension method for serialization purposes:
public static class TheHelper
{
public static string Serialize<T>(this T source, Encoding encoding)
{
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(T));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, encoding);
xs.Serialize(xmlTextWriter, source);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
return encoding.GetString(memoryStream.ToArray());
}
}
When sample Report object is created, it is next serialized to xml format:
Report r = new Report();
r.BirthDate.Published = true;
r.BirthDate.Value = DateTime.Now.AddYears(-1000).ToString("yyyy-MM-dd");
r.BirthPlace.Published = false;
r.BirthPlace.Value = "K-PAX";
string xml = r.Serialize(Encoding.UTF8);
Output document shown below is created:
<?xml version="1.0" encoding="utf-8"?>
<Report xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<BirthDate published="true">1011-04-07</BirthDate>
<BirthPlace published="false">K-PAX</BirthPlace>
</Report>
But I would like to add language identification using special attribute named xml:lang:
<?xml version="1.0" encoding="utf-8"?>
<Report xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<BirthDate published="true" xml:lang="en-GB">1011-04-07</BirthDate>
<BirthDate published="true" xml:lang="kp-AX">07.04.1011</BirthDate>
<BirthPlace published="false" xml:lang="en-GB">K-PAX</BirthPlace>
<BirthPlace published="false" xml:lang="kp-AX">k_p4x</BirthPlace>
</Report>
What can be the smart way to achieve this ? I have resources defined for en-GB and kp-AX.. languages. How to modify and create Report object to have multiple tags with different xml-lang attributes to be serializable using XmlSerializer ?
Regards.
This should work:
If you wanted to use the
CultureInfoclass, you could create a property and use theXmlIgnoreattribute on theCultureInfoproperty and have an addition string property that converts it, like in this LocalizableString example: