【发布时间】:2019-09-16 05:32:28
【问题描述】:
<?xml version="1.0"?>
<MainClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Items>
<Settings xsi:type="FileModel">
<Name>FileOne</Name>
<IsActive>true</IsActive>
<IsHidden>false</IsHidden>
</Settings>
<Settings xsi:type="FileModel">
<Name>FileTwo</Name>
<IsActive>true</IsActive>
<IsHidden>false</IsHidden>
</Settings>
<Settings xsi:type="ServerModel">
<Name>DelRep</Name>
<IsActive>false</IsActive>
<IsHidden>false</IsHidden>
</Settings>
</Items>
<DirectoryPath>D:\MainFolder</DirectoryPath>
</MainClass>
我有上面的 XML 文件。我试图在“D:\MainFolder”中存在的一组子文件夹的名称与上述 XML 中的元素之间进行比较。如果位置 D:\MainFolder 中不存在某个文件夹,我想删除该给定名称的整个设置元素。
例如,如果没有名为 FileOne 的子文件夹,我想要整个 XML 代码垃圾
<Settings xsi:type="FileModel">
<Name>FileOne</Name>
<IsActive>true</IsActive>
<IsHidden>false</IsHidden>
</Settings>
待删除
现在我将 XML 中的名称存储为
List<string> namesInXML = settingsFile.Descendants("Items").Elements("Settings ").Where(x => x.Attribute(nameSpace + "type").Value == "FileModel").Select(x => x.Element("Name").Value).ToList();
以及 D:\MainFolder 中的子文件夹
获得自:-
IEnumerable<string> fileNames = new DirectoryInfo(Path).EnumerateFiles("fileServer.config", SearchOption.AllDirectories).Select(fi => fi.DirectoryName).Select(dirPath => dirPath.Substring(Path.Length));
保存在此列表中
List<string> subFolderNames = fileNames.ToList();
如何使用这两个列表两个来满足我的要求?
【问题讨论】:
-
Linq 是专为读取(而不是写入或删除)而设计的查询。最好使用 for 循环: foreach(string nameInXml in settingsFile.Descendants("Items").Elements("Settings ").Where(x => x.Attribute(nameSpace + "type").Value == " FileModel")) { nameInXml.Remove();}。使用 for 循环来创建列表。
标签: c# xml serialization linq-to-xml