从 XML 序列化数组中删除包装元素 [英] Removing Wrapper Elements from XML-Serialized Array
问题描述
我使用的是 VSTS2008 + C# + .Net 3.0.我使用下面的代码来序列化 XML,我的对象包含数组类型属性,但是我想从生成的 XML 文件中删除一些额外的元素层(在我的示例中,MyInnerObject 和 MyObject).有什么想法吗?
I am using VSTS2008 + C# + .Net 3.0. I am using below code to serialize XML, and my object contains array type property, but there some additional elements' layer (in my sample, MyInnerObject and MyObject) generated which I want to remove from the generated XML file. Any ideas?
当前生成的 XML 文件,
Current generated XML file,
<?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 文件,
Expected XML file,
<?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 命令提示符):
To figure this out in the future, you can run (from a VS Command Prompt):
xsd.exe test.xml
xsd.exe /classes test.xsd
这会生成 test.cs,其中包含基于 xml 的 xml 可序列化类.如果你有一个 .xsd,当然效果会更好
This generates test.cs, that contains the xml serializable class, based on the xml. This works even better if you have an .xsd around ofcourse
这篇关于从 XML 序列化数组中删除包装元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!