<?xml version="1.0" encoding="UTF-8"?>
<ConfigurationFile>
<ConfigurationFilePath>Test1</ConfigurationFilePath>
<ConnectionString>Test2</ConnectionString>
<AnalyzefilePath>Test3</AnalyzefilePath>
</ConfigurationFile>
我想获得每个领域的信息.
但这并没有显示任何东西..
这是我的C#代码背后:
private void ParseXMLFile()
{
Console.WriteLine("Parse");
if (configurationPAthFileTextBox.Text != null)
{
Console.WriteLine("file != null");
try
{
XElement main = XElement.Load(configurationPAthFileTextBox.Text);
var results = main.Descendants("ConfigurationFile")
.Select(e => new { ConfigurationFilePath = e.Descendants("ConfigurationFilePath").FirstOrDefault().Value,
ConnectionString = e.Descendants("ConnectionString").FirstOrDefault().Value });
foreach (var result in results)
Console.WriteLine("{0}, {1}", result.ConfigurationFilePath, result.ConnectionString);
Console.ReadLine();
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
}
}
}
解决方法:
>将其加载为XDocument,因为它是文档,而不是元素.
var xDoc = XDocument.Load(configurationPAthFileTextBox.Text);
>您可以轻松地将文档转换为字典< string,string>将元素名称作为键,将元素值作为值:
var results = xDoc.Root
.Elements()
.ToDictionary(e => e.Name, e => (string)e);
>要打印ConfigurationFilePath和ConnectionString:
Console.WriteLine("{0}, {1}", results["ConfigurationFilePath"], results["ConnectionString"]);
打印Test1,Test2.