我想将 C# 类结构序列化为 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; }
}