Click here to Skip to main content
15,569,696 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi.

I need to create an xml like this:

XML
<SalesTable class="entity">
	<SalesLine class="entity">
		<ItemId>1</ItemId>
	</SalesLine>
	<SalesLine class="entity">
		<ItemId>2</ItemId>
	</SalesLine>
    <SalesLine class="entity">
		<ItemId>3</ItemId>
	</SalesLine>
</SalesTable>


What I have tried:

I have the class SalesTable:
C#
public class SalesTable
    {
        [XmlAttribute(AttributeName = "class")]
        public string Clase { get; set; }
        public SalesLine[] SalesLine = new SalesLine[2];
}


And the class SalesLine

C#
public class SalesLine
    {
        [XmlAttribute(AttributeName = "class")]
        public string Clase { get; set; }
        public string ItemId { get; set; }
}


I use it like this
C#
for (int i = 0; i < 3; i++)
{
  SalesTable.SalesLine[i] = new SalesLine();
  SalesTable.SalesLine[i].Clase = "entity"
  SalesTable.SalesLine[i].ItemId=i;
}
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(SalesTable.GetType());


But this generates one more element with the name of the array

XML
<SalesTable class="entity">
   <SalesLine>
	  <SalesLine class="entity">
		 <ItemId>1</ItemId>
	  </SalesLine>
	  <SalesLine class="entity">
		<ItemId>2</ItemId>
	  </SalesLine>
      <SalesLine class="entity">
		<ItemId>3</ItemId>
	  </SalesLine>
    </SalesLine>
</SalesTable>


I thought of renaming the array as SalesTable but I need it to have the class="entity" atributte:
XML
<SalesTable class="entity">
	<SalesLine class="entity">
		<ItemId>1</ItemId>
	</SalesLine>
	<SalesLine class="entity">
		<ItemId>2</ItemId>
	</SalesLine>
    <SalesLine class="entity">
		<ItemId>3</ItemId>
	</SalesLine>
</SalesTable>


How could I do it?

thanks a lot
Posted
Updated 27-Jan-22 4:22am

1 solution

Add the element attribute on SalesLine property in your SalesTable class, like:

public class SalesTable
    {
        [XmlAttribute(AttributeName = "class")]
        public string Clase { get; set; }
        [XmlElement(ElementName = "SalesLine")]
        public SalesLine[] SalesLine = new SalesLine[2];
    }
    public class SalesLine
    {
        [XmlAttribute(AttributeName = "class")]
        public string Clase { get; set; }
        public string ItemId { get; set; }
    }


Output:
<SalesTable class="Sales">
	<SalesLine class="entity">
		<ItemId>0</ItemId>
	</SalesLine>
	<SalesLine class="entity">
		<ItemId>1</ItemId>
	</SalesLine>
</SalesTable>
 
Share this answer
 
Comments
Juan Pele 31-Jan-22 9:28am    
Thanks, it works perfectly
M Imran Ansari 31-Jan-22 9:53am    
Great. Happy Coding!!

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