【问题标题】:Draw Comparison between List Obtained from XML File and List Obtained from SubFolders and Modifying XML File Accordingly比较从XML文件中获取的列表和从子文件夹中获取的列表并据此修改XML文件
【发布时间】: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


【解决方案1】:

通过这两个列表实现您的要求:

           namesInXML.ForEach(name =>
            {
                if (!subFolderNames.Contains(name))
                {
                    settingsFile.Descendants("Items").Elements("Settings").
                    Where(x => x.Attribute(nameSpace + "type").Value == "FileModel" && x.Element("Name").Value.Equals(name)).
                    First().Remove();
                }
            });

【讨论】:

    【解决方案2】:

    您可以使用Except(); 删除文件夹名称

    var removingNames = namesInXML.Except(subFolderNames).ToList();
    

    然后从 XML 中删除这些名称;

    foreach (var item in removingNames)
    {
        settingsFile.Descendants("Items").Elements("Settings").
        Where(x => x.Attribute(nameSpace + "type").Value == "FileModel" && x.Element("Name").Value.Equals(item)).
        First().Remove();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-18
      • 2011-01-15
      • 1970-01-01
      • 2014-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多