用于插入记录(C#)的复杂XML结构
本文关键字:复杂 XML 结构 插入 记录 用于 | 更新日期: 2023-09-27 18:27:27
我需要写入结构复杂的XML文件。
我的有效xml结构如下所示。
<ads>
<ad id="00121" date="1/1/2016 01:01:59" >
<adinfo title="" email="" phone="" rOD="" rPrice="" rat="" cdetails="" address="" postal="" />
<adimg>
<img mail="T" src=""/>
<img mail="F" src=""/>
<img mail="F" src=""/>
</adimg>
</ad>
<ad id="00121" date="1/1/2016 01:01:59" >
<adinfo title="" email="" phone="" rOD="" rPrice="" rat="" cdetails="" address="" postal="" />
<adimg>
<img mail="T" src=""/>
<img mail="F" src=""/>
<img mail="F" src=""/>
</adimg>
</ad>
....
....
</ads>
我已经阅读了本教程http://www.dotnetperls.com/xmlwriter
但上面的教程是针对简单的XML结构的。
正如您所看到的,我的XML有点复杂。
例如,我需要在父ads
元素中插入ad
我应该使用什么以及如何解决这个问题?
thnx
使用functional construction
方法创建新元素;它非常简单,您可以使用此技术创建任何类型的复杂元素。
将字符串XML转换为XDocument
xDoc = XDocument.Parse(xml);
//xml contains string value of XML
创建新XElement
XElement xElement = new XElement("ad",
new XAttribute("id", 00121),
new XAttribute("date", "1/1/2016 01:01:59"),
new XElement ("adinfo",
new XAttribute("title", ""),
new XAttribute("phone", "")
//Add more attributes
),
new XElement("adimg",
new XElement("img",
new XAttribute("mail", "F")
//Add more attributes
)
//Add more XElements
)
);
将新创建的XElement添加到文档根元素
xDoc.Element("ads").Add(xElement);
保存到文件
xDoc.Save("xmlFile.xml");
--SJ