【问题标题】:not sure how to use XmlNode in C#不知道如何在 C# 中使用 XmlNode
【发布时间】:2013-08-06 04:50:55
【问题描述】:

在 C# 中,我需要使用 XmlNode 从这些属性中获取值,如下所示:

根元素 (ServerConfig):

  • 类型

  • 版本

  • 创建日期

子节点(项目):

  • 姓名

  • 来源

  • 目的地

XML:

<?xml version="1.0" encoding="utf-8"?>
<ServerConfig type="ProjectName" version ="1.1.1.2" createDate ="2013-07-30T15:07:19.3859287+02:00" >
<items>
    <item  name="fs" type="directory" source="C:\temp\source" destination="C:\temp\target" action="Create" />
    <item  name="testdoc.txt" type="file" source="C:\temp\source" destination="C:\temp\target" action="Update" />
</items>
</ServerConfig>

C#:

        XmlTextReader reader = new XmlTextReader(fileManager.ConfigFile);
        XmlDocument doc = new XmlDocument();
        XmlNode node = doc.ReadNode(reader);

        // failed to get values here
        var Version = node.Attributes["version"].Value;
        var Type = node.Attributes["type"].Value;
        var Date = node.Attributes["createDate"].Value;

        //how to get values from items/item attributes here?

非常感谢您的示例代码:)

【问题讨论】:

标签: c# xml xmldocument xmlnode


【解决方案1】:

您可以使用LINQ to XML(在最新的 .Net 版本中更可取)

var xdoc = XDocument.Load(fileManager.ConfigFile);
var serverConfig = xdoc.Root;
string version = (string)serverConfig.Attribute("version");
DateTime date = (DateTime)serverConfig.Attribute("createDate");
string type = (string)serverConfig.Attribute("type");

var items = from item in serverConfig.Element("items").Elements()
            select new {
                Name = (string)item.Attribute("name"),
                Type = (string)item.Attribute("type"),
                Source = (string)item.Attribute("source"),
                Destination = (string)item.Attribute("destination")
            };

看一下 - 几行代码和文件被解析为强类型变量。甚至 date 也是 DateTime 对象而不是字符串。 items 是匿名对象的集合,其属性对应于 xml 属性。

【讨论】:

    【解决方案2】:

    你可以使用XmlSerializer:

    类:

    public class ServerConfig
    {
        public ServerConfig()
        {
            Items = new List<Item>();
        }
    
        [XmlAttribute("type")]
        public string Type { get; set; }
    
        [XmlAttribute("version")]
        public string Version { get; set; }
    
        [XmlAttribute("createDate")]
        public DateTime CreateDate { get; set; }
    
        [XmlArray("items")]
        [XmlArrayItem("item")]
        public List<Item> Items { get; set; }
    }
    
    public class Item
    {
        [XmlAttribute("name")]
        public string Name { get; set; }
    
        [XmlAttribute("type")]
        public string Type { get; set; }
    
        [XmlAttribute("source")]
        public string Source { get; set; }
    
        [XmlAttribute("destination")]
        public string Destination { get; set; }
    
        [XmlAttribute("action")]
        public string Action { get; set; }
    }
    

    例子:

    var data = @"<?xml version=""1.0"" encoding=""utf-8""?>
        <ServerConfig type=""ProjectName"" version =""1.1.1.2"" createDate =""2013-07-30T15:07:19.3859287+02:00"" >
        <items>
            <item  name=""fs"" type=""directory"" source=""C:\temp\source"" destination=""C:\temp\target"" action=""Create"" />
            <item  name=""testdoc.txt"" type=""file"" source=""C:\temp\source"" destination=""C:\temp\target"" action=""Update"" />
        </items>
        </ServerConfig>";
    
    var serializer = new XmlSerializer(typeof(ServerConfig));
    
    ServerConfig config;
    
    using(var stream = new StringReader(data))
    using(var reader = XmlReader.Create(stream))
    {
        config = (ServerConfig)serializer.Deserialize(reader);
    }
    

    【讨论】:

      【解决方案3】:

      您应该使用 XPath 来获取项目并在结果上循环;)

      类似这样的:

      foreach (XmlNode item in doc.DocumentElement.SelectNodes("items/item"))
      {
        var Name = item.Attributes["name"].Value;
        var Source= item.Attributes["source"].Value;
        var Destination = item.Attributes["destination"].Value;
      } 
      

      要获取您的根元素,您可以使用doc.DocumentElement ;)

      【讨论】:

        【解决方案4】:

        加载您的文档:

        XmlDocument doc = new XmlDocument();
        doc.Load(fileManager.ConfigFile);
        

        然后您将能够使用 XPath 选择任何内容:

        doc.SelectSingleNode(XPath); 
        doc.SelectNodes(XPath);
        

        【讨论】:

          【解决方案5】:

          我不会使用XmlNode,而是使用XmlElement,因为它有一个名为GetAttribute(string attributeName) 的好方法,它比XmlNode 上的Attributes 索引器属性更容易使用。而且,由于XmlElement 派生自XmlNode,因此您在保留基本XmlNode 类的功能的同时获得了附加功能。..

          var items = doc.DocumentElement.SelectNodes("items/item").Cast<XmlElement>().ToList();
          
          // You can iterate over the list, here's how you'd get your attributes:
          var Name = items[0].GetAttribute("name"); // Returns null if attribute doesn't exist, doesn't throw exception
          var Source = items[0].GetAttribute("source");
          var Destination = items[0].GetAttrubite("destination");
          

          HTH。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-05-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-11-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多