使用 c# 动态构建 XML [英] Build XML Dynamically using c#

查看:27
本文介绍了使用 c# 动态构建 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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. 如果有相同元素的集合 (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**           
                )
            )
        )
    );

推荐答案

LINQ 可以派上用场:

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)
              )
          )
      );

这篇关于使用 c# 动态构建 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆