在C#中创建文件并写入XML

3

我正在为Windows 10 Mobile编写UWP应用程序。

我创建了以下这样的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", "1");
        el.SetAttribute("PayStateID", "0");
        el.SetAttribute("Remark", "{StreetName} , ..");
        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", "");
        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"));

我想创建一个.xml文件并将xml写入其中。

我尝试像这样保存它 doc.Save("data.xml"); 但出现以下错误

Error   CS1503  Argument 1: cannot convert from 'string' to 'System.IO.Stream'  Murakami    

我该怎么做呢?

非常感谢您的帮助!


1
你试过搜索如何保存XmlDocument吗?你会得到很多结果! - Charles Mager
1
可能是如何使用XmlDocument创建XML文档?的重复问题。 - Charles Mager
@CharlesMager 这是一个通用应用程序。 - Adriano Repetti
@ЕвгенийСухомлин 这里有一些关于这个问题的SO帖子,我没有找到完全相同的重复,所以我只是给你一个例子:https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/XmlDocument - Adriano Repetti
2个回答

2

如果你正在编写Windows 10通用应用程序,那么XmlDocument.Save(string)将无法使用。相反,请使用

    using (FileStream fs = new FileStream("test.xml", FileMode.Create))
    {
        doc.Save(fs);
    }

这个解决方案是否有效?对我来说,它会出现未经授权的访问错误。 - Kiran Paul
嗨,我只是想提一下,我在Ubuntu 16.04上使用Core Net 1.0工作时遇到了同样的错误。但是当我这样做时,它让我保留了XML。非常感谢。 - JPCS

1

由于您正在开发Windows通用应用程序。

您需要使用以下代码将文件保存在存储中:

StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile file = await folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
await doc.SaveToFileAsync(file);

错误 CS1503:参数 1:无法将类型为 'string' 的对象转换为类型 'System.IO.Stream'。出现了这个错误。 - user5677145
请查看此解决方案。在UWP中,这种方式可以帮助您保存XML文件。 - Saadi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接