如何从XML文件中读取文件名和版本并将其添加到字典中

时间:2013-06-09 07:05:43

标签: c# asp.net oop

我有一个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>

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

using System.Xml.Linq; 

然后你可以将XML文件加载到这样的XDocument ......

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

或者,如果您已经在字符串变量中使用XML,则可以执行此操作...

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);
相关问题