我使用的是VSTS2008 + C#+ .Net 3.0。我使用下面的代码来序列化XML,我的对象包含数组类型属性,但是生成了一些其他元素的图层(在我的示例中,MyInnerObject和MyObject),我想从生成的XML文件中删除它。有什么想法吗?
当前生成的XML文件
<?xml version="1.0"?>
<MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MyObjectProperty>
<MyObject>
<MyInnerObjectProperty>
<MyInnerObject>
<ObjectName>Foo Type</ObjectName>
</MyInnerObject>
</MyInnerObjectProperty>
</MyObject>
</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>
<MyInnerObjectProperty>
<ObjectName>Foo Type</ObjectName>
</MyInnerObjectProperty>
</MyObjectProperty>
</MyClass>
当前代码,
public class MyClass
{
private MyObject[] _myObjectProperty;
[XmlArrayItemAttribute(IsNullable=false)]
public MyObject[] MyObjectProperty
{
get
{
return _myObjectProperty;
}
set
{
_myObjectProperty = value;
}
}
}
public class MyObject
{
private MyInnerObject[] _myInnerObjectProperty;
[XmlArrayItemAttribute(IsNullable = false)]
public MyInnerObject[] MyInnerObjectProperty
{
get
{
return _myInnerObjectProperty;
}
set
{
_myInnerObjectProperty = value;
}
}
}
public class MyInnerObject
{
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[1];
instance.MyObjectProperty[0] = new MyObject();
instance.MyObjectProperty[0].MyInnerObjectProperty = new MyInnerObject[1];
instance.MyObjectProperty[0].MyInnerObjectProperty[0] = new MyInnerObject();
instance.MyObjectProperty[0].MyInnerObjectProperty[0].ObjectName = "Foo Type";
s.Serialize(fs, instance);
return;
}
}
答案 0 :(得分:14)
而不是
[XmlArrayItemAttribute]
使用:
[XmlElement]
为了将来解决此问题,您可以(从VS命令提示符)运行:
xsd.exe test.xml
xsd.exe /classes test.xsd
这将生成test.cs,其中包含基于xml的xml可序列化类。如果您在课程周围有.xsd,那么效果会更好。