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?
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>
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>
Current code,
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;
}
}
Instead of
[XmlArrayItemAttribute]
use:
[XmlElement]
To figure this out in the future, you can run (from a VS Command Prompt):
xsd.exe test.xml
xsd.exe /classes test.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With