使用 C# 动态构建 XML
我必须根据用户输入动态创建一个 XML 文件。
这是我的想法,但我遇到了两个问题。
- 如果存在相同元素的集合(MaxOccurs = 10) (例如,如果用户输入了 4 个帐户,那么我的代码应该如何)
- 如果有一个选择选项。根据所选元素,子元素应该发生变化。
有人请帮助我。
提前感谢
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**
)
)
)
);
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.
- if there is a collection of same element (MaxOccurs = 10)
(For example if the user entered 4 accounts then how should my code be) - 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**
)
)
)
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
LINQ 可以在处理以下事情时派上用场:
LINQ comes in handy for things like this:
使用 XmlWriter 对象代替,至少在我看来是这样更容易做你想做的事情。然后你可以将其构造如下:
Use an XmlWriter object instead, at least imo it is easier to do the sort of things you want. You can then structure it something like:
或者为要转换为 XML 的每种类型创建一个类并使用 XmlSerializer。
Or create a class for each type that you want to convert to XML and use the XmlSerializer.