我正在使用 VSTS2008 + C# + .Net 3.0。我正在使用下面的代码序列化 XML,并且我的对象包含数组类型属性,但是生成了一些我想从生成的 XML 文件中删除的附加元素层(在我的示例中,MyInnerObject 和 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>
<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;
}
}
最佳答案
代替
[XmlArrayItemAttribute]
使用:
[XmlElement]
为了将来解决这个问题,您可以运行(从 VS 命令提示符):
xsd.exe test.xml
xsd.exe /classes test.xsd
这会生成 test.cs,其中包含基于 xml 的 xml 可序列化类。如果你有一个 .xsd 的话,效果会更好
关于c# - 从 XML 序列化数组中删除包装元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1227693/