【发布时间】:2009-08-04 10:07:01
【问题描述】:
我正在使用 C# + VSTS2008 + .Net 3.0 进行 XML 序列化。代码工作正常。下面是我的代码和当前的序列化 XML 结果。
现在我想在输出 XML 文件中添加两个附加层。这是我预期的 XML 结果。有什么简单的方法可以做到这一点?我不确定 NestingLevel 是否可以帮助做到这一点。我想找到一种不改变 MyClass 和 MyObject 结构的简单方法。
预期的 XML 序列化结果,
<?xml version="1.0"?>
<MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MyObjectProperty>
<AdditionalLayer1>
<AdditionalLayer2>
<ObjectName>Foo</ObjectName>
</AdditionalLayer1>
</AdditionalLayer2>
</MyObjectProperty>
</MyClass>
当前 XML 序列化结果,
<?xml version="1.0"?>
<MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MyObjectProperty>
<ObjectName>Foo</ObjectName>
</MyObjectProperty>
</MyClass>
我当前的代码,
public class MyClass
{
public MyObject MyObjectProperty;
}
public class MyObject
{
public string ObjectName;
}
public class Program
{
static void Main(string[] args)
{
XmlSerializer s = new XmlSerializer(typeof(MyClass));
FileStream fs = new FileStream("foo.xml", FileMode.Create);
MyClass instance = new MyClass();
instance.MyObjectProperty = new MyObject();
instance.MyObjectProperty.ObjectName = "Foo";
s.Serialize(fs, instance);
return;
}
}
【问题讨论】:
标签: c# .net xml visual-studio-2008 xml-serialization