【问题标题】:Create file and write xml there (C#)创建文件并在那里写入 xml (C#)
【发布时间】:2016-05-06 06:43:39
【问题描述】:

我正在为 Windows 10 移动版编写 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    

我怎样才能做到这一点?

非常感谢您的帮助!

【问题讨论】:

标签: c# xml win-universal-app


【解决方案1】:

由于您正在编写 Windows 10 通用应用程序,XmlDocument.Save(string) 不可用。相反,使用

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

【讨论】:

  • 这个解决方案有效吗?对我来说,它给出了未经授权的访问错误
  • 嗨,我只是想提一下,我在 ubuntu 16.04 中使用 core net 1.0 并且出现了同样的错误。但是当我这样做时,我会保持 xml 非常感谢你
【解决方案2】:

因为您正在开发 Windows 通用应用程序。

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

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

【讨论】:

  • 错误 CS1503 参数 1:无法从 'string' 转换为 'System.IO.Stream' 有这个错误。 ——
  • 请看这个解决方案。在 UWP 中,这种方式可以帮助您保存 xml 文件。
猜你喜欢
  • 1970-01-01
  • 2013-08-27
  • 1970-01-01
  • 2011-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-22
相关资源
最近更新 更多