在我的程序中,我正在检查是否存在xml文件。如果文件不存在,我只是在指定的目录中创建它,然后尝试将另一个xml的内容复制到新的xml文件中。同样,如果文件存在,我将复制另一个文件的内容并覆盖现有文件。当我运行我的应用程序并检查目录时,我想要复制xml代码的文件也说“XML文档必须有一个顶级元素。错误处理资源”。
到目前为止,我已经尝试过:System.IO.File.Copy(sourceFile,targetPath);用于文件复制。
我的代码块看起来与此类似:
string sourceFile= "C:\\fileIWantToCopy.xml;
string targetpath= "C:\\NeedsFilledWithSourceContents.xml;
if (File.Exists(targetPath) == false) {
File.Create(targetPath);
System.IO.File.Copy(sourceFile, targetPath, true);
} else {
System.IO.File.Copy(sourceFile, targetPath, true);
}
XDoc.Save(String.Format(targetPath));
我还需要一些提示,告诉我如何将一个xml文件的内容复制到另一个新创建的文件中,而不需要“XML文档必须具有顶级元素。错误处理资源”错误。我的源xml文档的第一行是:
< ? xml version =“1.0”encoding =“utf-8”? >
然后进行典型的头部/身体构造。
在将内容复制到新文件之前,是否需要将内容写入新文件?
由于
答案 0 :(得分:3)
使用System.IO
文件操作复制现有文件或保存内存中的XDocument
。但两者兼顾完全没有意义!
if (File.Exists(sourceFile)) {
System.IO.File.Copy(sourceFile, targetPath, true);
} else {
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XComment("This is a test"),
new XElement("root")
);
doc.Save(targetPath);
}
如果您想保存XDocument
这个就足够了,不需要提前创建文件。
doc.Save(targetPath);
MSDN上的说明
XDocument.Save(String)
将此XDocument序列化为文件,覆盖现有文件(如果存在)。
所有节点必须嵌入单个根节点(任何名称都可以),并且至少必须存在根节点
行
<?xml version="1.0" encoding="utf-8" ?>
<html>
<head />
<body />
</html>
错误(两个根节点)
<?xml version="1.0" encoding="utf-8" ?>
<head />
<body />
错误(没有根节点)
<?xml version="1.0" encoding="utf-8" ?>
另外,我没有看到String.Format
有什么用,没有其他参数。
我也不喜欢if (File.Exists(targetPath) == false)
。更好:if (!File.Exists(targetPath))
。更好的是,扭转条件以获得积极的问题
if (File.Exists(targetPath)) {
System.IO.File.Copy(sourceFile, targetPath, true);
} else {
File.Create(targetPath);
System.IO.File.Copy(sourceFile, targetPath, true);
}