[英]Build XML Dynamically using c#
我必须根据用户输入动态创建XML文件。
这是我想出来的,我有两个问题。
有人请帮帮我。
提前致谢
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对于这样的事情派上用场:
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)
)
)
);
使用XmlWriter对象,至少可以更容易地做你想要的事情。 然后你可以构造它像:
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
或者为要转换为XML的每种类型创建一个类,并使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.