3
我想將C#類結構序列化爲XML,並提供特定的節點名稱,而不必擁有一堆嵌套類。這有可能使用屬性?是否可以使用屬性指定XML節點名稱和深度
例如說我有以下XML:
<OuterItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<InnerItem>
<ItemValue>something i need</ItemValue>
</InnerItem>
</OuterItem>
我有一個XML序列化方法,看起來像這樣:
public static string XmlSerializeToString<T>(T value)
{
if (value == null) { return null; }
XmlSerializer serializer = new XmlSerializer(typeof(T));
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = false;
settings.OmitXmlDeclaration = true;
using (StringWriter textWriter = new StringWriter())
using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
{
serializer.Serialize(xmlWriter, value);
return textWriter.ToString();
}
}
我就必須有一個C#類結構是怎樣的呢?
public class OuterItem
{
public InnerItem InnerItem { get; set; }
}
public class InnerItem
{
public string ItemValue { get; set; }
}
或者是它在所有可能的聲明我的節點應該怎麼遠了XML文檔中像這樣的東西(僞代碼):
public class OuterItem
{
[XmlNode("InnerItem\ItemValue")]
public string ItemValue { get; set; }
}