如果在我的 WPF 项目中找不到 xml 文件,如何编写创建新的 xml?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13192963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write the create new xml if the xml file is not found in my WPF project?
提问by 0070
I currently using an WPF app. Right now, i want to save my data into the XML file. If the xml file is not found in the project, then create a new one. Does anyone can teach me how?
我目前使用 WPF 应用程序。现在,我想将我的数据保存到 XML 文件中。如果在项目中找不到 xml 文件,则创建一个新文件。有没有人可以教我怎么做?
i think the code will be something like this
我认为代码将是这样的
public MainWindow()
{
InitializeComponent();
loadXML();
}
public void loadXML()
{
xDocument doc = xDocument.load("MyXmlFile.xml");
if(doc.exist== false)
{
//create new xml
}
}
回答by dash
The simplest thing do to in this instance is to use File.Existsto check if the file actually exists on disk. If it doesn't, then we can save it, otherwise we load it:
在这种情况下,最简单的做法是使用File.Exists来检查文件是否确实存在于磁盘上。如果没有,那么我们可以保存它,否则我们加载它:
public void loadXML()
{
XDocument document = new XDocument();
if(!File.Exists("MyXmlFile.xml")){
//Populate with data here if necessary, then save to make sure it exists
document.Save("MyXmlFile.xml");
}
else{
//We know it exists so we can load it
document.load("MyXmlFile.xml");
}
//Continue to work with document
}

