将xml写入文件

本文关键字:文件 xml | 更新日期: 2023-09-27 18:25:35

我知道这里有很多相同的问题,但它不能解决我的问题

我想把xml写入文件。在Xamarin上编写Android应用程序。

我已经创建了

我创建这样的xml:

XmlDocument doc = new XmlDocument();
XmlElement el = (XmlElement)doc.AppendChild(doc.CreateElement("Order"));
el.SetAttribute("CallConfirm", "1");
el.SetAttribute("PayMethod", "Безнал");
el.SetAttribute("QtyPerson", "");
el.SetAttribute("Type", "2");
el.SetAttribute("PayStateID", "0");
el.SetAttribute("Remark", "{Comment}");
el.SetAttribute("RemarkMoney", "0");
el.SetAttribute("TimePlan", "");
el.SetAttribute("Brand", "1");
el.SetAttribute("DiscountPercent", "0");
el.SetAttribute("BonusAmount", "0");
el.SetAttribute("Department", "");
XmlElement el2 = (XmlElement)el.AppendChild(doc.CreateElement("Customer"));
el2.SetAttribute("Login", "");
el2.SetAttribute("FIO", "{FIO}");
XmlElement el3 = (XmlElement)el.AppendChild(doc.CreateElement("Address"));
el3.SetAttribute("CityName", "{CityName}");
el3.SetAttribute("StationName", "");
el3.SetAttribute("StreetName", "{StreetName}");
el3.SetAttribute("House", "{HouseName}");
el3.SetAttribute("Corpus", "");
el3.SetAttribute("Building", "");
el3.SetAttribute("Flat", "{FlatName}");
el3.SetAttribute("Porch", "");
el3.SetAttribute("Floor", "");
el3.SetAttribute("DoorCode", "");
XmlElement el4 = (XmlElement)el.AppendChild(doc.CreateElement("Phone"));
el4.SetAttribute("Code", "{Code}");
el4.SetAttribute("Number", "{Phone}");
XmlElement el5 = (XmlElement)el.AppendChild(doc.CreateElement("Products"));
XmlElement el6 = (XmlElement)el5.AppendChild(doc.CreateElement("Product"));
el6.SetAttribute("Code", "{ProductCode}");
el6.SetAttribute("Qty", "{QTY}");
Console.WriteLine ("TUT");
Console.WriteLine(doc.OuterXml);

我试着写这样的文件:

File.WriteAllText("myFile.xml",doc.ToString());

并且有这个错误-Access to the path "/myFile.xml" is denied.

我试着这样写文件,但无济于事。

我在设备上看不到文件(尝试通过浏览器查找)

 var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var filePath = Path.Combine(documentsPath, "myFile.xml");
File.WriteAllText(filePath, doc.ToString());

我该如何解决这个问题?

感谢的帮助

将xml写入文件

您似乎试图用无效路径保存文件:/myFile.xml

尝试使用完全限定的路径,方法如下:

var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var filePath = Path.Combine(documentsPath, "myFile.xml");
File.WriteAllText(filePath, doc.ToString());