【问题标题】:How to read file names and versions from XML file and add them into dictionary如何从 XML 文件中读取文件名和版本并将它们添加到字典中
【发布时间】:2013-06-09 07:05:43
【问题描述】:

我在文件标签中有一个 Xml 文件和文件名和版本.....我想读取所有文件名及其对应的版本,然后想将它们添加到字典中

<application name="AutoUpdator" url="\\server\setups\AutoUpdator" version="1.1.0.0" updatedOn= "9-6-2013">
<InfoConfigFile name="InfoFile" version="1.1.0.0" />
<file name="Core0.txt" version="1.1.0.0" source="\\server\setups\AutoUpdator\1.1.0.0\bin\Core0.txt"/>
<file name="Core1.txt" version="1.1.0.0" source="\\server\setups\AutoUpdator\1.1.0.0\bin\Core1.txt"/>
<file name="Core2.txt" version="1.1.0.0" source="\\server\setups\AutoUpdator\1.1.0.0\bin\Core2.txt"/>
<file name="Core3.txt" version="1.1.0.0" source="\\server\setups\AutoUpdator\1.1.0.0\bin\Core3.txt"/>
<file name="Core4.txt" version="1.0.0.0" source="\\server\setups\AutoUpdator\1.0.0.0\bin\Core4.txt"/>
<file name="Core5.txt" version="1.0.0.0" source="\\server\setups\AutoUpdator\1.0.0.0\bin\Core5.txt"/>
</files>
</application>

【问题讨论】:

  • 那么问题是什么?

标签: c# asp.net oop


【解决方案1】:

您可以使用LINQ to XML。首先在 C# 文件的顶部添加以下 using 语句(如果您还没有)...

using System.Xml.Linq; 

然后您可以像这样将 XML 文件加载到 XDocument...

XDocument document = XDocument.Load(@"C:\path\to\your\file.xml");

或者,如果您已经有 XML in string 变量,您可以这样做...

XDocument document = XDocument.Parse(xmlString);

如果您的 XML 中不能有重复的文件名,您可以像这样获取您的 Dictionary...

var dictionary = document.Root
                         .Element("files")
                         .Elements("file")
                         .ToDictionary(x => x.Attribute("name").Value,
                                       x => x.Attribute("version").Value);

【讨论】:

  • 我没有得到这里使用“x => x”的目的
  • 这是一个 lambda 表达式。您可以在Lambda Expressions (C# Programming Guide) 阅读有关它们的更多信息。它们是 LINQ 编程的关键部分,您可以在此处阅读更多信息:LINQ (Language-Integrated Query)
  • thnx davmos ... :) 我们可以使用 Xmlreader 解决这个问题吗?
  • 没问题,阿玛吉特。自从引入“LINQ to XML”以来,我很少使用XmlReader
【解决方案2】:

C# 有一个相当广泛的 XML 库可用。

您可能要查找的类称为 XmlReader,文档可在此处获得:

http://msdn.microsoft.com/en-us/library/system.xml.xmlreader(v=vs.71).aspx http://support.microsoft.com/kb/307548

您发布的示例文本中的每一行在 XML 中称为 元素,因此当您阅读上述链接中的文档时,XmlNodeType 元素对应于每一行。

您要解析的信息、文件名和版本被称为 attributes,它们与每一行的元素相关,因此当您阅读第二个链接中的示例代码时,请注意如何您可以从每个元素中提取属性。

在您的情况下,这两个术语足以使用现有方法轻松解析此文件。

就将这些放入字典而言,您可以简单地使用字典,但由于您熟悉该名称,您可能已经知道这一点。

http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-30
    • 2023-03-02
    • 2020-01-31
    • 2021-04-04
    • 2016-03-18
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多