Attribute based Linq query

To another challenge. I looked through some of the questions I found here, but I can’t put together what I need.

OK I have an XML file:

<Output id="1"> <path rename="Off" name="pattern-1">d:\temp</path> </Output> <Output id="2"> <path isRename="False" name="pattern-1" >d:\temp\out2</path> <path isRename="True" name="pattern-1" >d:\temp\out3</path> <path isRename="False" name="pattern-1">d:\temp\out4</path> </Output> 

I need to find the <Output> tag based on the id attribute. Then I need to skip all the <path> tags and get the attribute and path value. I tried several things based on the previous question that I asked, but I could not get it to work.

 var results = from c in rootElement.Elements("Output") where (string)c.Attribute("Id") == "2" select c; foreach (var path in rootElement.Elements("Output").Elements("path")) { string p = path.Value; } 
+4
source share
2 answers

Your first line does nothing unless you actually use the results.

 foreach (var outputElement in rootElement.Elements("Output") .Where(e => (string)e.Attribute("id") == "1")) { foreach (var pathElement in outputElement.Elements("path")) { // ... } } 

If your id attribute is guaranteed to be unique (as it should), you can get rid of the first foreach and just get the individual <Output> directly:

 var outputElement = rootElement.Elements("Output") .FirstOrDefault(e => (string)e.Attribute("id") == "1")); 
+1
source

I would recommend using some XPath to select the nodes you need:

 foreach (XElement path in root.XPathSelectElements("/Output/path[../@id=1]")) { string value = path.Value; } 

Indeed, sometimes XPath allows you to write more readable and customizable code. You just use some expression that replaces several linq-to-xml statements.

0
source

Source: https://habr.com/ru/post/1396097/


All Articles