Creating XML dynamically using C #

I need to create an XML file dynamically based on user input.

This is what I came up with, and I ran into two problems.

  • if there is a collection of the same element (MaxOccurs = 10) (For example, if the user entered 4 accounts, then how should my code be)
  • If there is a selection option. Based on the selected item, child items must be modified.

Someone please help me.

Thank you in advance

BB

My code is:

XElement req = new XElement("order", new XElement("client", new XAttribute("id", clientId), new XElement("quoteback", new XAttribute ("name",quotebackname) ) ), new XElement("accounting", new XElement("account"), new XElement("special_billing_id") ), new XElement("products", new XElement( **productChoiceType**, ***** HERE THE ELEMENTS WILL CHAGE BASED ON **productChoiceType** ) ) ) ); 
+4
source share
3 answers

LINQ comes in handy for things like this:

 XElement req = new XElement("order", new XElement("client", new XAttribute("id",clientId), new XElement("quoteback", new XAttribute ("name",quotebackname)) ), new XElement("accounting", new XElement("account"), new XElement("special_billing_id") ), new XElement("products", new XElement(productChoices.Single(pc => pc.ChoiceType == choiceType).Name, from p in products where p.ChoiceType == choiceType select new XElement(p.Name) ) ) ); 
+6
source

Use an XmlWriter instead, at least it's easy for them to do what you want. Then you can create it somehow:

 XmlWriter w = XmlWriter.Create(outputStream); w.WriteStartElement("order"); w.WriteStartElement("client"); w.WriteAttributeString("id", clientId); // ... w.WriteElementString("product", "1"); w.WriteElementString("product", "2"); w.WriteElementString("product", "3"); w.WriteElementString("product", "4"); // etc.... w.WriteEndElement(); // client w.WriterEndElement(); // order 
+1
source

Or create a class for each type that you want to convert to XML, and use the XmlSerializer.

 <XmlElement("order")> _ Public Class Order <XmlElement("accounting")> _ Dim accounts As List(Of Account) ... End Class Dim xmlSer as New XmlSerialzer(GetType(Accounting)) xmlSer.Serialize(myXmlWriter, myObjInstance) 
0
source

All Articles