I’m some what new to linq could uses some help..
I have an xml file that looks like this:
<InputPath>
<path isRename="Off" isRouter="Off" pattern="pattern-1">d:\temp1</path>
<path isRename="Off" isRouter="pattern-1">d:\temp2</path>
</InputPath>
I need to loop through and get the key values of the tag “path”.
What I have so far is
var results = from c in rootElement.Descendants("InputPath") select c;
foreach (XElement _path in results)
{
string value = _path.Element("path").Value;
}
But I only get the last <path> value. Any help would be great.
You’ll only get the first element that way, because that’s what the
Elementmethod gives you: the first child element with the given name.If you want multiple elements you can just use
Elementsinstead:Alternatively, use the
Elementsextension method and do it all in one go:If that doesn’t help, please give more information about what you’re trying to do and what the problem is.
If by “last” you mean “the element contents” that’s because you’re using the
Valueproperty. If you want the attributes within the path element, you need theAttributemethod, as shown by IamStalker, although personally I’d usually cast theXAttributeto string (or whatever) rather than using theValueproperty, in case the attribute is missing. (It depends on what you want the behaviour to be in that case.)