Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build XML Dynamically using c#

Tags:

c#

xml

xelement

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

Here is what I came up with and I am struck up with two issues.

  1. if there is a collection of same element (MaxOccurs = 10) (For example if the user entered 4 accounts then how should my code be)
  2. If there is a choice option. Based on the element chosen the child elements should change.

Somebody please help me.

Thanks in advance

BB

My code :

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**           
                )
            )
        )
    );
like image 994
BumbleBee Avatar asked Feb 25 '23 19:02

BumbleBee


1 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)
              )
          )
      );
like image 197
StriplingWarrior Avatar answered Mar 08 '23 04:03

StriplingWarrior