我正在Windows商店中制作一个应用程序,并且在创建的xml文件中编写xml时遇到问题。我已在Windows Store App中遵循此Editing XML文件,但对我而言不起作用。
我希望在单击按钮时将此xml写入我的xml文件中。
这个东西的任何替代方法..
<drink>
<drinkImage>ck.png</drinkImage>
<drinkTitle>COKE</drinkTitle>
<drinkDescription>(1793-1844)</drinkDescription>
</drink>
我当前的文件是这样的:
<?xml version="1.0" encoding="utf-8" ?>
<drinks>
<drink>
<drinkImage>pepsi.png</drinkImage>
<drinkTitle>PEPSI</drinkTitle>
<drinkDescription>(1793-1844)</drinkDescription>
</drink>
**<here I Want above xml on button click>**
</drinks>
这是我尝试过的:
namespace DrinksApp
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class coke : Page
{
public coke()
{
this.InitializeComponent();
}
XmlDocument dom = new XmlDocument();
private void Button_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(softdrinks));
}
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
XDocument xmlDoc = XDocument.Load("favourite//fav.xml");
xmlDoc.Root.Add(new XElement("drink",
new XAttribute("drinkImage","ck.png"),
new XAttribute("drinkTitle","PEPSI"),
new XAttribute("drinkDescription","NONE")
));
xmlDoc.Save(xmlDoc); **//This isn't working in windows store ..**
}
}
}
}
在控制台应用程序中编写了此代码,但它仍适用于Windows Store应用程序。
XDocument xdoc = XDocument.Load("fa.xml");
xdoc.Root.Add(new XElement("drink",
new XElement("drinkImage", "Img.png"),
new XElement("drinkTitle", "NewDrink"),
new XElement("drinkDescription", "HelloWorld")));
xdoc.Save("fa.xml");
输出:
<?xml version="1.0" encoding="utf-8"?>
<drinks>
<drink>
<drinkImage>pepsi.png</drinkImage>
<drinkTitle>PEPSI</drinkTitle>
<drinkDescription>(1793-1844)</drinkDescription>
</drink>
<drink>
<drinkImage>Img.png</drinkImage>
<drinkTitle>NewDrink</drinkTitle>
<drinkDescription>HelloWorld</drinkDescription>
</drink>
</drinks>
您的原始代码非常接近您想要的代码。您使用的是“ XAttribute”而不是“ XElement”。这不是问题,但是输出看起来像这样……
<drink drinkImage="ck.png" drinkTitle="PEPSI" drinkDescription="NONE" />
您的实际问题是保存。XDoucment.Save接受流,文本编写器,xml编写器或字符串。在此示例中,我使用了字符串路径。在此处查看更多信息:https : //msdn.microsoft.com/zh-cn/library/system.xml.linq.xdocument(v=vs.110).aspx
编辑:尝试使用文件流:
var xmlFile = await StorageFile.GetFileFromPathAsync("fav.xml");
using (var fileStream = await xmlFile.OpenStreamForWriteAsync())
{
xdoc.Save(fileStream);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句