这是我想要的xml文件。它包含灾难详情numbere 01,02,03及以后。灾难由灾难身份确定。
<?xml version="1.0" encoding="utf-8" ?>
<disasters>
<disaster ID="001"
disaterType="Flood"
location="Matara"
date="20-01-2012"
noOfVictims="245">
<victims>
<victim type="adult"
gender="male"
amount="46"
/>
<victim type="children"
gender="female"
amount="460"/>
</victims>
<requiredItems>
<requiredItem type="Food"
itemName="Rice"
description="null"
quantity="367"/>
<requiredItem type="Stationary"
itemName="Pens"
description="null"
quantity="87"/>
</requiredItems>
</disaster>
<disaster ID="002" // This is a separate disaster detail list
disaterType="Tsunami"
location="Galle"
date="10-05-2009"
noOfVictims="845">
<victims>
<victim type="children"
gender="male"
amount="46"
/>
<victim type="children"
gender="female"
amount="460"/>
</victims>
<requiredItems>
<requiredItem type="Clothes"
itemName="Tshirts"
description="male"
quantity="67"/>
<requiredItem type="Food"
itemName="bread"
description="null"
quantity="37"/>
</requiredItems>
</disaster> // end of the second list of disaster details
</disasters>
这是我的代码。但它只添加了新的灾难ID。其余细节附加不正确。 **代码将附加到第一个灾难ID,但我想将它们添加到第二个灾难并将其识别为新灾难。 提前致谢
if (System.IO.File.Exists(path))
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load("C:\\4 ITP la laaa\\me doing\\disasters.xml");
XmlNode xNode = xDoc.CreateNode(XmlNodeType.Element, "disaster", "");
XmlAttribute id = xDoc.CreateAttribute("ID");
XmlAttribute disaterType = xDoc.CreateAttribute("value");
XmlAttribute location = xDoc.CreateAttribute("value1");
XmlAttribute date = xDoc.CreateAttribute("value2");
XmlAttribute noOfVictims = xDoc.CreateAttribute("value3");
id.Value = "001";
disaterType.Value = "Flood";
date.Value = " value1";
noOfVictims.Value = "date";
xNode.Attributes.Append(id);
xNode.Attributes.Append(disaterType);
--
--
XmlNode xNode1 = xDoc.CreateNode(XmlNodeType.Element, "victims", "");
XmlAttribute type = xDoc.CreateAttribute("type");
type.Value = "adult";
gender.Value = "male";
value.Value = "46";
--
--
xDoc.GetElementsByTagName("disasters")[0].InsertAfter(xNode, xDoc.GetElementsByTagName("disasters")[0].LastChild);
**xDoc.GetElementsByTagName("victims")[0].InsertAfter(xNode1, xDoc.GetElementsByTagName("victims")[0].LastChild);**
xDoc.Save("C:\\4 ITP la laaa\\me doing\\disasters.xml");
Label1.Text=("Apended");
答案 0 :(得分:0)
您的代码似乎太复杂了。我只修复了**
一个。
xDoc.GetElementsByTagName("disasters")[0].InsertAfter(xNode,
xDoc.GetElementsByTagName("disasters")[0].LastChild);
//xDoc.GetElementsByTagName("victims")[0].InsertAfter(xNode1,
// xDoc.GetElementsByTagName("victims")[0].LastChild);
xNode.AppendChild(xNode1); // <visitors> is simply a direct child of <disaster>
using System.Xml.Linq;
XDocument xDoc = XDocument.Load("ExistingFile.xml");
XElement newDisaster = new XElement("disaster",
new XAttribute("ID", 2),
new XAttribute("location", "Galle"),
...
new XElement("victims",
new XElement("victim",
new XAttribute("type", "children"),
...
)));
xDoc.Element("disasters").Add(newDisaster);
xDoc.Save("SomeFileName.xml");