假设我有一个简单的类型:
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; }
}
我为序列化目的定义了简单的扩展方法:
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());
}
}
创建示例Report对象时,接下来将其序列化为xml格式:
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);
创建如下所示的输出文档:
<?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>
但我想使用名为 xml:lang 的特殊属性添加language identification:
<?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>
实现这一目标的聪明方法是什么?我有为en-GB和kp-AX ..语言定义的资源。如何修改和创建Report对象,使多个带有不同xml-lang属性的标记可以使用XmlSerializer进行序列化?
问候。
答案 0 :(得分:1)
这应该有效:
public class Element
{
[XmlAttribute("published")]
public bool Published { get; set; }
[XmlAttribute("xml:lang", DataType = "language")]
public string Language { get; set; }
[XmlText]
public string Value { get; set; }
}
如果你想使用CultureInfo
类,你可以创建一个属性并使用XmlIgnore
属性上的CultureInfo
属性,并有一个可以转换它的附加字符串属性,就像在这个LocalizableString示例:
/// <summary>
/// The language of the <see cref="Value"/>
/// </summary>
[XmlIgnore]
public CultureInfo Language { get; set; }
/// <summary>Used for XML serialization.</summary>
/// <seealso cref="Language"/>
[XmlAttribute("xml:lang", DataType = "language")]
public string LanguageString
{
get { return (Language == null || string.IsNullOrEmpty(Language.ToString())) ?
null : Language.ToString(); }
set { Language = string.IsNullOrEmpty(value) ?
CultureInfo.InvariantCulture : new CultureInfo(value); }
}