我的XML文件如下所示:
<root>
<files>
<filesource uploadName="20180131T083441_638_Test.doc" originalName="Test.doc">c:\uploadDir\20180131T083441_638_Test.doc</filesource>
<filesource uploadName="20180131T083441_638_Test1.doc" originalName="Test1.doc">c:\uploadDir\20180131T083441_638_Test1.doc</filesource>
<filesource uploadName="20180131T083441_638_Test2.doc" originalName="Test2.doc">c:\uploadDir\20180131T083441_638_Test2.doc</filesource>
</files>
</root>
C#代码:
// fileNodes has all 3 files sources
XmlNode filesNodes = xmlFile.findNode("/root/files");
List<string> filenames = new List<string>();
filesname.add("c:\uploadDir\20180131T083441_638_Test.doc");
filesname.add("c:\uploadDir\20180131T083441_638_Test1.doc");
无论变量filenames
包含什么,我想将其保存在XML文件中,其余的我想删除。
答案 0 :(得分:0)
使用过的xml linq。不得不从文件名中删除文件夹名称以使代码生效
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication23
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
List<string> filenames = new List<string>();
filenames.Add(@"c:\uploadDir\20180131T083441_638_Test.doc");
filenames.Add(@"c:\uploadDir\20180131T083441_638_Test1.doc");
List<string> baseFilenames = filenames.Select(x => x.Substring(x.LastIndexOf("\\") + 1)).ToList();
XDocument doc = XDocument.Load(FILENAME);
List<XElement> filesources = doc.Descendants("filesource").ToList();
foreach (XElement filesource in filesources)
{
string uploadName = (string)filesource.Attribute("uploadName");
if (!baseFilenames.Contains(uploadName))
filesource.Remove();
}
}
}
}