Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list of node that there attribute

I need a list of all the Attribute ID(the value) of Descendants(Frame) that have an Attribute SecondFeature (Descendants-ObjectClass) that equal Vehicle. (there is node that have 1 "object", other 2/3 time and other not at all) this is a part of the code:

<?xml version="1.0" encoding="utf-8" ?> 
- <Frame ID="120">
<PTZData Zoom="1.000" />
- <Object ID="5">
 <ObjectClass SecondFeature="vehicle" /> 
</Object>
</Frame>
like image 896
Rachel Botbol Avatar asked Aug 07 '26 01:08

Rachel Botbol


1 Answers

You can do it with following XPath expression:

var xml = // your XML string here
var doc = XDocument.Parse(xml);
var frameIds = doc.Root.XPathSelectElements(
        "//Frame[./Object/ObjectClass[@SecondFeature ='Vehicle']]")
    .Select(n => n.Attribute("ID").Value);

Naturally, if your Frame nodes can be present without ID attributes, you'll need extra null checks in .Select.

Alternatively, non-xpath appraoch (but this is IMHO less readable and calls for even more caution):

var frameIds = doc
    .Descendants("ObjectClass")
    .Where(n => n.Attribute("SecondFeature").Value == "Vehicle")
    .Select(n => n.Parent.Parent.Attribute("ID").Value);
like image 107
k.m Avatar answered Aug 09 '26 13:08

k.m



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!