我有一个XML世界地图,它基本上需要两个输入(它是一个带有相应CSS文件和内容的XML文件):国家/地区输入和国家/地区地址。因此,当我手动将数据输入XML文件(国家/地区名称和国家/地区)时,地图上的国家/地区会更改其颜色,并且将鼠标悬停在该国家/地区上时,我可以看到我输入的内容。
我的数据库中包含所有国家/地区的列表。所以我想我有办法从我的数据库中将所有这些国家写入XML文件。我在考虑这样的事情:
for(int i=0; i<list.count;i++)
{
list[i].CounryName = //write it into the XML file;
list[i].CountryUserAddress = //Write it into the XML file;
}
因此,想法是当for循环继续时,每个国家都写入XML文件。我在ASP.NET中使用XML文件方面没有任何重要经验,而且我在这里干涸了。所有这些都应该通过代码来完成。有人可以帮我解决这个问题,或者至少指出我正确的方向吗?
谢谢堆!
P.S。我忘了提到我应该覆盖现有的XML文件,而不是创建一个新文件...
答案 0 :(得分:0)
以下是您如何使用您提供的数据执行此操作的示例:
public string EditDoc()
{
string filename = "Path/MyFileName.xml";
List<string> list = new List<string>();
if (File.Exists(filename)) //we have the file, so update it
{
XmlDocument myDoc = new XmlDocument(); //create a document object
myDoc.Load(filename); //load existing info
XmlNode root = myDoc.DocumentElement; //the root node ("Country")
XmlNode nodeToUpdate = root.SelectSingleNode("CountryName"); //select the node to update
nodeToUpdate.Value = "new info"; //give it a new value
myDoc.Save(filename); //save the document
}
else //didn't find the file
{
XmlDocument myDoc = new XmlDocument(); //create a new document
XmlNode countryList = myDoc.CreateElement("CountryList");
myDoc.AppendChild(countryList);
for (int i = 0; i < list.Count; i++)
{
XmlNode country = myDoc.CreateElement("Country"); //create the parent "Country" element
myDoc.AppendChild(countryList); //append to the list
XmlNode countryName = myDoc.CreateElement("CountryName"); //create element for "CountryName"
countryName.AppendChild(myDoc.CreateTextNode(list[i].CountryName)); //add data from list index
country.AppendChild(countryName); //append this as a child to "Country"
XmlNode countryUserAddress = myDoc.CreateElement("CountryUserAddress"); //create element for "CountryUserAddress"
countryUserAddress.AppendChild(myDoc.CreateTextNode(list[i].CountryUserAddress)); //add data from list index
country.AppendChild(countryUserAddress); //append as a child to "Country"
}
myDoc.Save(filename); //save the document
}
}
一般的想法是遍历文档的树并选择要更新的值。可能有更好的方法来做到这一点,但这是我熟悉的方式。同样,您可以以相同的方式创建xml文档。
主题不同,但这有助于我理解阅读/编写XML数据:this link
编辑:我稍微更新了代码以使父元素“CountryList”并将DB中的每个“Country”附加到该元素。该文件将最终出现如下:
<CountryList>
<Country>
<CountryName>Blah</CountryName>
<CountryUserAddress>Blah</CountryUserAddress>
</Country>
<Country>
<CountryName>Blah</CountryName>
<CountryUserAddress>Blah</CountryUserAddress>
</Country>
</CountryList>