使用c#动态构建XML

Bum*_*Bee 4 c# xml xelement

我必须根据用户输入动态创建XML文件.

这是我想出来的,我有两个问题.

  1. 如果有一个相同元素的集合(MaxOccurs = 10)(例如,如果用户输入了4个帐户,那么我的代码应该如何)
  2. 如果有选择选项.根据所选元素,子元素应该改变.

有人请帮帮我.

提前致谢

BB

我的代码:

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**           
                )
            )
        )
    );
Run Code Online (Sandbox Code Playgroud)

Str*_*ior 6

LINQ对于这样的事情派上用场:

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)
              )
          )
      );
Run Code Online (Sandbox Code Playgroud)