Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placing a Property into a Different XML Namespace with XML Serialization

I am using VSTS2008 + C# + .Net 3.0. I am using below code to serialize XML, here is my current code and serialized XML file. My purpose is I want to make MyInnerObjectProperties belongs to a special XML namespace (http://foo/2009) and making this namespace as default namespace. Any ideas how to implement this?

Current output:

<?xml version="1.0"?>
<MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <MyObjectProperty>
    <MyInnerObjectProperties>
      <MyInnerObjectProperty>
        <ObjectName>Foo Type</ObjectName>
      </MyInnerObjectProperty>
      <MyInnerObjectProperty>
        <ObjectName>Goo Type</ObjectName>
      </MyInnerObjectProperty>
    </MyInnerObjectProperties>
  </MyObjectProperty>
</MyClass>

Current code:

public class MyClass
{
    private MyObject[] _myObjectProperty;

    [XmlElement(IsNullable=false)]
    public MyObject[] MyObjectProperty
    {
        get
        {
            return _myObjectProperty;
        }
        set
        {
            _myObjectProperty = value;
        }
    }
}
public class MyObject
{
    private MyInnerObject[] _myInnerObjectProperty;

    [XmlArrayItemAttribute("MyInnerObjectProperty", typeof(MyInnerObject),  IsNullable=false)]
    public MyInnerObject[] MyInnerObjectProperties
    {
        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].MyInnerObjectProperties = new MyInnerObject[2];
        instance.MyObjectProperty[0].MyInnerObjectProperties[0] = new MyInnerObject();
        instance.MyObjectProperty[0].MyInnerObjectProperties[0].ObjectName = "Foo Type";
        instance.MyObjectProperty[0].MyInnerObjectProperties[1] = new MyInnerObject();
        instance.MyObjectProperty[0].MyInnerObjectProperties[1].ObjectName = "Goo Type";

        s.Serialize(fs, instance);

        return;
    }
}
like image 463
George2 Avatar asked Feb 02 '26 13:02

George2


1 Answers

How about this:

[XmlArrayItemAttribute( Namespace = "http://foo.com/2009" /* other attr. params. */ )]
public MyInnerObject[] MyInnerObjectProperties
{
    get { ... }
    set { ... }
}
like image 129
azheglov Avatar answered Feb 04 '26 01:02

azheglov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!