Click here to Skip to main content
15,346,160 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi.
I need to build an xml like this

XML
<Dimension>
           <element>MM9</element>
           <element>JKS</element>
           <element>FFES</element>
</Dimension> 

The "element" attribute is repeated several times with the same name.
What would be the correct way to do it?

Thanks a lot.

Regards.

What I have tried:

I have tried creating the Dimension class and element attributes

<pre lang="C#">
public class Dimension

   {
       [XmlElement("element")]
       public string element1 { get; set; }
       [XmlElement("element")]
       public string element2 { get; set; }
       [XmlElement("element")]
       public string element3 { get; set;
} 


When I serialize the class I get an error for having attributes with the same name.

C#
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(Dimension.GetType());
x.Serialize(Console.Out, Dimension); 


i tried with a list
C#
public class element
    {
        [XmlElement("element")]
        public string element1 { get; set; }
    }

public List<element> Dimension = new List<element>();


But the result is not what I need
XML
<Dimension>
           <element>
            <element>MM9</element>
          </element>
</Dimension> 
Posted
Updated 29-Dec-21 2:38am
Comments
Richard MacCutchan 29-Dec-21 5:32am
   
If you have multiple element entries in the Dimension, then the element entry in the class should probably be an array of strings.
Juan Pele 29-Dec-21 7:04am
   
Hi Richard. Thank you for answering so quickly.

If I understood you correctly, you say to do something like that, right?

public List<string> element = new List<string>();

But if I do this the resulting xml:

<dimension>
<element>
<string>MM9
<string>JKS
<string>FFES





...and what I need is:
<dimension>
<element>MM9
<element>JKS
<element>FFES


Thanks a lot.

Regards.
Richard MacCutchan 29-Dec-21 7:18am
   
I suggested an array of Strings, I made no mention of List<t>.
Juan Pele 29-Dec-21 18:09pm
   
Sorry I misunderstood you. Using an array of Strings works correctly, Thanks a lot.

Regards.

1 solution

Take a look at this XML serialization documentation page[^]. As Richard mentioned in his comments, you can use an XmlArrayItem attribute to indicate a collection of values. Ie.
C#
public class Dimension
{
  [XmlArrayItem("element")]
  public string[] Elements { get; set; }
}
   
Comments
Juan Pele 29-Dec-21 18:06pm
   
Thank you very much now create the XML just as I needed it

Regards.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900