Answered Handling XML file using linq

jkeertir

Member
Joined
Apr 18, 2020
Messages
9
Programming Experience
1-3
Hi,
If I have following XML

<Test>
<Group name="aaa">
<DID value ="deep" table="1">
<Item i="1">
</Item>
</DID>
<DID value ="deep1" table="1">
<Item i="1">
</Item>
</DID>
</Group>
<Group name="bbb">
<DID value ="deep2" table="1">
<Item i="1">
</Item>
</DID>
<DID value ="deep3" table="1">
<Item i="1">
</Item>
</DID>
</Group>
</test>
If I have the .XML file as above ,how can I use linq and get the Group name value ie . "aaa" for DID whose value is "deep1"
 
Last edited:
Assuming you fix the data to valid XML by properly closing the Test element... go for the DID elements where 'value' attribute equals "deep1", then select 'name' attribute of Parent.
query syntax:
var doc = XDocument.Load("data.xml");

var result = (from x in doc.Descendants("DID")
              where x.Attribute("value").Value == "deep1"
              select x.Parent.Attribute("name").Value
              ).FirstOrDefault();
method syntax:
var result = doc.Descendants("DID")
                .Where(x => x.Attribute("value").Value == "deep1")
                .Select(x => x.Parent.Attribute("name").Value)
                .FirstOrDefault();

Use Insert button in editor and select type (Xml and other code languanges) for indented and formatted display:
insertcode.png
 
Back
Top Bottom