简体   繁体   English

C#使用LINQ解析简单的XML文件

[英]C# Parsing simple XML file with LINQ

I have this very simple xml file : 我有这个非常简单的xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<ConfigurationFile>
    <ConfigurationFilePath>Test1</ConfigurationFilePath>
    <ConnectionString>Test2</ConnectionString>
    <AnalyzeFilePath>Test3</AnalyzeFilePath>
</ConfigurationFile>

And I want to get informations of each field. 我想获得每个领域的信息。 But this doesn't display anything.. 但这并没有显示任何东西..

Here is my C# code behind : 这是我的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());
        }
    }
}
  1. Load it as XDocument , because it's a document, not an element. 将其加载为XDocument ,因为它是一个文档,而不是一个元素。

     var xDoc = XDocument.Load(configurationPAthFileTextbox.Text); 
  2. You can easily convert your document into Dictionary<string, string> with element names as keys and element values as values: 您可以轻松地将文档转换为Dictionary<string, string>其中元素名称为键,元素值为值:

     var results = xDoc.Root .Elements() .ToDictionary(e => e.Name, e => (string)e); 
  3. To print ConfigurationFilePath and ConnectionString : 要打印ConfigurationFilePathConnectionString

     Console.WriteLine("{0}, {1}", results["ConfigurationFilePath"], results["ConnectionString"]); 

    Prints Test1, Test2 . 打印Test1, Test2

First, create a class to represent the information of interest contained in your XML file. 首先,创建一个类来表示XML文件中包含的感兴趣的信息。 Define a constructor that extracts the values of interest from your XML file and maps them to the properties of your class: 定义一个构造函数,从XML文件中提取感兴趣的值,并将它们映射到类的属性:

public class ConfigurationFile
{
    public String ConfigurationFilePath { get; set; }
    public String ConnectionString { get; set; }
    public String AnalyzeFilePath { get; set; }

    public ConfigurationFile(String xmlFilePath)
    {
        XDocument document = XDocument.Load(xmlFilePath);
        var root = document.Root;

        ConfigurationFilePath = (string)root.Element("ConfigurationFilePath");
        ConnectionString = (string)root.Element("ConnectionString");
        AnalyzeFilePath = (string)root.Element("AnalyzeFilePath");
    }
}

Once you have created this class with its special constructor, making use of the class is very straightforward: 一旦用它的特殊构造函数创建了这个类,使用该类非常简单:

var configFile = new ConfigurationFile(xmlFilePath);

var path = configFile.ConfigurationFilePath;
var connectString = configFile.ConnectionString;
var analyzeFilePath = configFile.AnalyzeFilePath;

Here's a demonstration program that puts it all together. 这是一个将所有内容组合在一起的演示程序。 (Please note that in this demo program the constructor loads the XML from a string rather than from a file as shown above.) (请注意,在此演示程序中,构造函数从字符串而不是文件中加载XML,如上所示。)

using System;
using System.Xml;
using System.Xml.Linq;

class LinqToXmlDemo
{
    static public void Main(string[] args)
    {
        string xmlContent = GetXml();
        var configFile = new ConfigurationFile(xmlContent);

        Console.WriteLine
            ("ConfigurationFilePath:[{0}]\n" +
             "ConnectionString:[{1}]\n" +
             "AnalyzeFilePath:[{2}]\n--",
             configFile.ConfigurationFilePath,
             configFile.ConnectionString,
             configFile.AnalyzeFilePath);
    }

    static string GetXml()
    {
        return
            @"<?xml version='1.0' encoding='UTF-8'?>
              <ConfigurationFile>
                  <ConfigurationFilePath>Test1</ConfigurationFilePath>
                  <ConnectionString>Test2</ConnectionString>
                  <AnalyzeFilePath>Test3</AnalyzeFilePath>
              </ConfigurationFile>";
    }
}

public class ConfigurationFile
{
    public String ConfigurationFilePath { get; set; }
    public String ConnectionString { get; set; }
    public String AnalyzeFilePath { get; set; }

    public ConfigurationFile(String xml)
    {
        XDocument document = XDocument.Parse(xml);
        var root = document.Root;

        ConfigurationFilePath = (string)root.Element("ConfigurationFilePath");
        ConnectionString = (string)root.Element("ConnectionString");
        AnalyzeFilePath = (string)root.Element("AnalyzeFilePath");
    }
}

Expected Output 预期产出

ConfigurationFilePath:[Test1]
ConnectionString:[Test2]
AnalyzeFilePath:[Test3]
--

Simply, You can use too: 简单地说,您也可以使用:

string yourString = (string)(from element in xDocument.Root.Descendants("ConfigurationFilePath") select element).First();

=D = d

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM