【问题标题】:Filtering out attributes in XML file based of the XSI type of attrubutes根据属性的 XSI 类型过滤掉 XML 文件中的属性
【发布时间】:2019-09-11 10:12:02
【问题描述】:

我有一个如下结构的 XML 文档

<?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>FileRepository</Name>
      <IsActive>true</IsActive>
      <IsHidden>false</IsHidden>
    </Settings>
    <Settings xsi:type="FileModel">
      <Name>FileRepository</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>

这里我希望能够根据xsi类型对数据进行分类。例如,我想编写一个代码来删除 XSI 类型下的所有内容: FileModel 。在 C# 中可以这样做吗?

【问题讨论】:

    标签: c# xml serialization deserialization


    【解决方案1】:

    将 xml linq 与字典一起使用:

    using System;
    using System.Collections.Generic;
    using System.Collections;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    
    
    namespace ConsoleApplication131
    {
        class Program
        {
    
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {                
                XDocument doc1 = XDocument.Load(FILENAME);
                XElement root = doc1.Root;
                XNamespace xsiNs = root.GetNamespaceOfPrefix("xsi");
    
                Dictionary<string, List<XElement>> dict = doc1.Descendants("Settings")
                    .GroupBy(x => (string)x.Attribute(xsiNs + "type"), y => y)
                    .ToDictionary(x => x.Key, y => y.ToList());
    
                dict["FileModel"].Remove();
                dict.Remove("FileModel");
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-06
      • 1970-01-01
      • 2020-07-29
      相关资源
      最近更新 更多