简体   繁体   中英

C# Parsing simple XML file with LINQ

I have this very simple xml file :

<?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 :

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.

     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:

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

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

    Prints Test1, Test2 .

First, create a class to represent the information of interest contained in your XML file. Define a constructor that extracts the values of interest from your XML file and maps them to the properties of your class:

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.)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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