【问题标题】:How to read XML data dynamically in C#/.net?如何在 C#/.net 中动态读取 XML 数据?
【发布时间】:2012-05-28 17:25:36
【问题描述】:

如何动态读取 XML 数据?如何尽可能通用和动态地管理我的 C# 代码?根据要求,我将需要在 Xml 中添加更多文件夹路径,这不应该以必须重写的方式影响编写的代码..

给定一段 XML 作为示例:

<?xml version="1.0" standalone="yes"?>
  <HOSTS>
   <Host id = '1'>
     <Extension>txt</Extension>
     <FolderPath>C:/temp</FolderPath>
   </Host>
   <Host id = '2'>
     <Extension>rar</Extension>
     <FolderPath>C:/Sample</FolderPath>
   </Host>
 </HOSTS>

如何动态读取主机 ID?我有什么可能?

【问题讨论】:

    标签: c# .net xml


    【解决方案1】:

    是的 - 实际上这是 C# 中非常常见的任务。

    有几种方法可以解决这个问题:

    这些链接应该为您指明正确的方向。

    【讨论】:

      【解决方案2】:

      使用 LINQ to XML。

      示例:检索具有 (id = 1) 的主机:

      string id = "1"
      
      
      XDocument doc = XDocument.Load("data.xml");
      var accounts = from elements in doc.Elements("HOSTS").Elements("Host")
                      where elements.Attribute("id").Value = id
                          select elements.FirstOrDefault();
      

      【讨论】:

        【解决方案3】:

        从该示例 xml 生成一个 xsd 方案。根据需要对其进行修改,然后使用xsd.exe 生成一个强类型的 C# 类。

        【讨论】:

          【解决方案4】:

          最好的办法是将System.Xml.XmlDocument 类与System.Xml.XmlDocument.Load(...) 一起用于构造函数。

          【讨论】:

            【解决方案5】:

            对于这种情况,最好的方法(在我看来)是对强类型类使用 XML 序列化。您可以使用Attributes 控制进程。

            var serializer = new XmlSerializer(typeof(Hosts));
            var hosts = (Hosts)serializer.Deserialize(new StringReader(str));
            

            ...

            [XmlRoot("HOSTS")]
            public class Hosts : List<Host> {}
            
            public class Host {
                [XmlAttribute("id")]
                public int Id { get; set; }
            
                public string Extension { get; set; }
            
                public string FolderPath { get; set; }
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-06-12
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多