0

Im serializing my class to XML. I have an issue with the root element of one of my classes is NOT being named properly.

The complete XML structure should look like the following.

<Workflow>
  <Name>My Workflow</Name>
  <Description />
  <Modules>
    <Module Name="Intro" MenuText="IntroText" />
  </Modules>
</Workflow>

However Im getting this result

<Workflow>
  <Name>My Workflow</Name>
  <Description />
  <Modules>
    <WorkflowModule Name="Intro" MenuText="IntroText" />
  </Modules>
</Workflow>

I want the element "WorkflowModule" to be called "Module" however the problem is that I already have another class called Module. So to get around this problem I called it a WorkflowModule and put a class XmlRoot() declartion like so;

[XmlRoot("Module")]
public class WorkflowModule
{...}

But when I serialize the Workflow class it still comes up with WorkflowModule.

Here are my 2 classes classes;

[XmlRoot("Workflow")]
public class Workflow
{

    private string _name;
    private string _description;
    private List<WorkflowModule> _modules = new List<WorkflowModule>();



    [XmlElement("Name")]
    public String Name
    {
        get {  }
        set {  }
    }


    [XmlElement("Description")]
    public String Description
    {
        get {  }
        set {  }
    }


    [XmlArrayItem(typeof(WorkflowModule))]
    public List<WorkflowModule> Modules
    {
        get { }
        set { }
    }
}








[XmlRoot("Module")]
public class WorkflowModule
{

    private string _name;
    private string _menu_text;


    public WorkflowModule()
    {
    }


    [XmlAttribute("Name")]
    public String Name
    {
        get { }
        set { }

    }


    [XmlAttribute("MenuText")]
    public String MenuText
    {
        get { }
        set { }

    }

}

}

IEnumerable
  • 3,610
  • 14
  • 49
  • 78

2 Answers2

2

Set the element name within XmlArrayItem attrubute:

[XmlArrayItem(typeof(WorkflowModule), ElementName = "Module")]
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
1

There are many ways to control it as defined in this duplicate post How do I Set XmlArrayItem Element name for a List<Custom> implementation?

These attribute control serialize from the this object's perspective as it transverses nested objects

[XmlArray("RootArrayElementNameGoesHere")]
[XmlArrayItem(typeof(Workflow), ElementName="ArrayItemElementNameGoesHere")]
public List<WorkflowModule> Modules

This attribute redefining the element name but can be overwritten with the local [XmlArrayItem] or [XmlElement] attributes to provides local override from the owning objects serialization

[XmlType(TypeName = "UseThisElementNameInsteadOfClassName")]
public class WorkflowModule

This attribute is only honored when its the direct object being serialized

[XmlRoot("UseThisElementNameWhenItIsTheRoot")]
public class WorkflowModule
Community
  • 1
  • 1
Steve
  • 1,995
  • 2
  • 16
  • 25