既存の XML ファイルにデータを挿入しようとしています。次のコードがあります。
string file = MapPath("~/XMLFile1.xml");
XDocument doc;
//Verify whether a file is exists or not
if (!System.IO.File.Exists(file))
{
doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
new System.Xml.Linq.XElement("Contacts"));
}
else
{
doc = XDocument.Load(file);
}
foreach (var c in MyContactsLst)
{
//var contactsElement = new XElement("Contacts",
var contactsElement = new XElement("Contact",
new XElement("Name", c.FirstOrDefault().DisplayName),
new XElement("PhoneNumber", c.FirstOrDefault().PhoneNumber.ToString()),
new XElement("Email", "abc@abc.com"));
doc.Root.Add(contactsElement);
doc.Save(file);
}
最初の問題はコードの最初の行にあります。つまりMapPath("~/XMLFile1.xml");
、エラーが発生します
名前 'MapPath' は現在のコンテキストに存在しません
2番目の問題はdoc.Save(file);
エラーです
「System.Xml.Linq.XDocument.Save(System.IO.Stream)」に最適なオーバーロードされたメソッドの一致には、無効な引数がいくつかあります
この質問を参照しました asp.netの既存のxmlファイルにデータを挿入する方法は?
私はXMLを学んでいます。それで、どうすればこれを解決できますか?