假设,我有一个简单的类型:
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());
}
}
创建示例报表对象后,接下来会将其序列化为 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>
但我想添加 language identification使用名为 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>
实现这一目标的明智方法是什么?我有为 en-GB 和 kp-AX.. 语言定义的资源。如何修改和创建 Report 对象以具有多个具有不同 xml-lang 属性的标记,以便使用 XmlSerializer 进行序列化?
问候。
这应该有效:
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
类,您可以创建一个属性并在 CultureInfo
属性上使用 XmlIgnore
属性,并添加一个字符串属性来转换它,如 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); }
}
我是一名优秀的程序员,十分优秀!