简体   繁体   中英

How to get the value of elements using XML and Linq based off a specific tag name

Essentially, I have tried everything and for some reason I can't get the value of the elements in my XML based off the parameter I need it to meet. I feel like I'm close but I just don't know where I'm going wrong. I'm trying to get the value of the elements and put them into a list to be used elsewhere. Currently it doesn't put anything in the list.

I've tried XML Reader so now I'm giving Linq to XML a try but this won't work either.

private List<string> outputPath = new List<string>();
var doc = XDocument.Load(Path.Combine(projectDirectory, "JobPaths.xml"));
foreach (var child in doc.Element("Jobs").Elements("Job").Where(x => x.Attribute("Name").ToString() == jobName).Elements())
{
    outputPath.Add(child.Name.ToString());
}

return outputPath;

Here's the XML:

<?xml version="1.0" encoding="utf-8" ?>
<Jobs>
  <Job Name="events_monitoring_c">
    <Path>\\stadb4412\</Path>
  </Job>
  <Job Name="events_monitoring_d">
    <Path>\\stadb4412\</Path>
    <Path>\\stadb1111\</Path>
    <Path>\\stadb2412\</Path>
  </Job>
</Jobs>

The jobName comes from the XML File, so I'm trying to get all the path elements based on the job name, regardless of how many there are. I want to get all the paths in the list to be used elsewhere.

To find nodes of a specific type/tag from an XDocument or XElement you use .Descendants(name), then you have .Attribute(name) that returns an XAttribute. To get its value, you use .Value, not .ToString().

Your code gets the Job elements, but then it gets the children elements as an IEnumerable of nodes and for each of them adds the Name of the tags, which is always Path.

What you are looking for is doc.Descendants("Job").Where(job=>job.Attribute("Name")?.Value==jobName).SelectMany(job=>job.Elements()).Select(elem=>elem.Value).ToList();

I did it without compiling, so I may be wrong.

You parse into a dictionary using Xml Linq :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<string, List<string>> dict = doc.Descendants("Job")
                .GroupBy(x => (string)x.Attribute("Name"), y => y)
                .ToDictionary(x => x.Key, y => y.Elements("Path").Select(z => (string)z).ToList());
        }
    }
}

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