在c#中将整个xml文件复制到其他xml中

时间:2013-01-23 01:00:10

标签: c# xml xml-parsing

我有这个xml文件:http://www.studiovincent.net/list.xml

我需要在其他xml文件中复制整个内容。

我试过这段代码:

string sourcefile = "http://www.studiovincent.net/list.xml";
string destinationfile = "test.xml";
System.IO.File.Copy(sourcefile, destinationfile);

但不起作用,因为我收到此错误:不支持URI格式。

我如何解决这个问题?

2 个答案:

答案 0 :(得分:5)

File.Copy()不支持http://协议,因此URI formats are not supported错误。

您可以通过将页面内容读入字符串,然后将其写入文件来解决此问题。

WebClient client = new WebClient();
string contents = client.DownloadString("http://www.studiovincent.net/list.xml");

// write contents to test.xml
System.IO.File.WriteAllText ("test.xml", contents);

请注意WriteAllText()如果不存在则会创建test.xml,如果存在则会覆盖它。您还需要将上述代码包装在try / catch块中,并捕获并处理相应的删除。

答案 1 :(得分:2)

我建议使用WebClient.DownloadFile。下载字符串然后保存它可能会导致字符集映射出现问题。

WebClient client = new WebClient();
client.DownloadFile("http://www.studiovincent.net/list.xml", "test.xml");

这会直接复制文件而不是将数据转换为字符串,这可能会执行一些字符串转换(例如,文件是Unicode,WebClient认为它是UTF-8)然后复制到文件