c# - 不确定如何在 C# 中使用 XmlNode

标签 c# xml xmldocument xmlnode

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

根元素 (ServerConfig):

  • 类型

  • 版本

  • 创建日期

子节点(Items):

  • 姓名

  • 来源

  • 目的地

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?

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

最佳答案

您可以使用 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 属性。

关于c# - 不确定如何在 C# 中使用 XmlNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18058872/

相关文章:

android - 与 Admob 和 Webview 重叠

c# - 比较 XmlDocument 是否相等(内容方面)

c# - 如何以编程方式修改 app.config 中的 assemblyBinding?

objective-c - merge Xcode 项目文件

c# - 如何正确使用双引号?

c# - Windows Phone 8中BitmapImage/Image控件的内存消耗

c# - 在 MVC3 中绑定(bind)嵌套集合

c# - 无法对来自 xml 的数据执行乘法

C# 绑定(bind)值与数据库不匹配

c# - 使用 LINQ,获取导航属性的前 x 行的方法是什么?