Reading specific XML parameter

2019-09-14 16:24发布

问题:

I'm currently working on a project in which a xml file must be read for program settings.

The XML looks like this:

<?xml version="1.0" encoding="utf-8"?>
<!-- Settings for Modul1 -->
<root>
 <Program-Config>
  <Parameter>Name</Parameter>
  <Value>John</Value>
 </Program-Config>

 <Program-Config>
  <Parameter>Device</Parameter>
  <Value>TV</Value>
 </Program-Config>
.
.
.
</root>

This structure is also used to fill a datagridview like this:

Parameter | Value
__________|______
Name      | John
Device    | TV

This is working and I can save the changes I make to a xml file.

However my problem is that I need to read out a specific element of the xml file and yet it is not working so good.

My code:

        string dir;
        dir = Directory.GetCurrentDirectory() + "\\config.xml";

        XDocument xDoc = XDocument.Load(dir);
        var xmlStr = File.ReadAllText(dir);

        var str = XElement.Parse(xmlStr);
        var result = str.Elements("Program-Config").
            Where(x => x.Element("Parameter").Value.Equals("Device")).ToList();


        for (int i = 0; i <= result.Count - 1; i++)
        {
            Console.WriteLine(result[i].Value);
        }

But what he writes in Console is: DeviceTV . But I need: TV

This is then used as string / int whatever for other parts of the program.

Can anyone help me with that?

回答1:

The Value property returns the concatenated text of its child nodes. The element returned by result[i] is a Parameter element, but you want its child Value element only.

var value = (string) str.Elements("Program-Config")
    .Where(x => (string) x.Element("Parameter") == "Device")
    .Elements("Value")
    .Single();

It's not clear why you're doing XDocument.Load and throwing this away. You could use the document by tweaking your query slightly:

var value = (string) xDoc.Descendants("Program-Config")
    .Where(x => (string) x.Element("Parameter") == "Device")
    .Elements("Value")
    .Single();

See this fiddle for a working demo.