C#使用LINQ解析简单XML文件
我有一个非常简单的xml文件:C#使用LINQ解析简单XML文件,c#,xml,wpf,linq,linq-to-xml,C#,Xml,Wpf,Linq,Linq To Xml,我有一个非常简单的xml文件: <?xml version="1.0" encoding="UTF-8"?> <ConfigurationFile> <ConfigurationFilePath>Test1</ConfigurationFilePath> <ConnectionString>Test2</ConnectionString> <AnalyzeFilePath>Test3<
<?xml version="1.0" encoding="UTF-8"?>
<ConfigurationFile>
<ConfigurationFilePath>Test1</ConfigurationFilePath>
<ConnectionString>Test2</ConnectionString>
<AnalyzeFilePath>Test3</AnalyzeFilePath>
</ConfigurationFile>
XDocument
,因为它是一个文档,而不是一个元素
var xDoc = XDocument.Load(configurationPAthFileTextbox.Text);
字典
,元素名称作为键,元素值作为值:
var results = xDoc.Root
.Elements()
.ToDictionary(e => e.Name, e => (string)e);
配置文件路径
和连接字符串
:
Console.WriteLine("{0}, {1}", results["ConfigurationFilePath"], results["ConnectionString"]);
打印Test1、Test2
首先,创建一个类来表示XML文件中包含的感兴趣的信息。定义一个构造函数,用于从XML文件中提取感兴趣的值并将其映射到类的属性:
公共类配置文件
{
公共字符串配置文件路径{get;set;}
公共字符串连接字符串{get;set;}
公共字符串AnalyzeFilePath{get;set;}
公共配置文件(字符串xmlFilePath)
{
XDocument document=XDocument.Load(xmlFilePath);
var root=document.root;
ConfigurationFilePath=(字符串)root.Element(“ConfigurationFilePath”);
ConnectionString=(string)root.Element(“ConnectionString”);
AnalyzeFilePath=(字符串)root.Element(“AnalyzeFilePath”);
}
}
使用其特殊构造函数创建此类后,使用该类非常简单:
var configFile=新配置文件(xmlFilePath);
var path=configFile.ConfigurationFilePath;
var connectString=configFile.ConnectionString;
var analyzeFilePath=configFile.analyzeFilePath;
这里有一个演示程序,它将所有内容整合在一起。(请注意,在这个演示程序中,构造函数从字符串而不是如上所示的文件加载XML。)
使用系统;
使用System.Xml;
使用System.Xml.Linq;
类LinqToXmlDemo
{
静态公共void Main(字符串[]args)
{
字符串xmlContent=GetXml();
var configFile=新配置文件(xmlContent);
控制台写入线
(“ConfigurationFilePath:[{0}]\n”+
“连接字符串:[{1}]\n”+
“AnalyzeFilePath:[{2}]\n--”,
configFile.ConfigurationFilePath,
configFile.ConnectionString,
configFile.AnalyzeFilePath);
}
静态字符串GetXml()
{
返回
@"
测试1
测试2
测试3
";
}
}
公共类配置文件
{
公共字符串配置文件路径{get;set;}
公共字符串连接字符串{get;set;}
公共字符串AnalyzeFilePath{get;set;}
公共配置文件(字符串xml)
{
XDocument document=XDocument.Parse(xml);
var root=document.root;
ConfigurationFilePath=(字符串)root.Element(“ConfigurationFilePath”);
ConnectionString=(string)root.Element(“ConnectionString”);
AnalyzeFilePath=(字符串)root.Element(“AnalyzeFilePath”);
}
}
预期产出
ConfigurationFilePath:[Test1]
ConnectionString:[Test2]
AnalyzeFilePath:[Test3]
--
简单地说,您也可以使用:
string yourString = (string)(from element in xDocument.Root.Descendants("ConfigurationFilePath") select element).First();
=D
string yourString = (string)(from element in xDocument.Root.Descendants("ConfigurationFilePath") select element).First();