我必须根据用户输入动态创建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**
)
)
)
);
答案 0 :(得分: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)
)
)
);
答案 1 :(得分:2)
使用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
答案 2 :(得分:0)
或者为要转换为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)