I need to determine value using LINQ to XML query?
<?xml version="1.0" encoding="utf-8" ?>
<MYROOT>
<Group name="G1">
<Skill name="G1Skill1">
<SubSkill>G1skill1sub1</SubSkil开发者_JS百科l>
<SubSkill>G1skill1sub2</SubSkill>
</Skill >
<Skill name="G1Skill2">
<SubSkill>G1skill2sub1</SubSkill>
<SubSkill>G1skill2sub2</SubSkill>
</Skill >
</Group>
<Group name="G2">
<Skill name="G2Skill1">
<SubSkill>G2skill1sub1</SubSkill>
<SubSkill>G2skill1sub2</SubSkill>
</Skill >
<Skill name="G2Skill2">
<SubSkill>G2skill2sub1</SubSkill>
<SubSkill>G2skill2sub2</SubSkill>
</Skill >
</Group>
</MYROOT>
For e.g .
Inputs are "G1"
& "G1skill1sub1"
Expected output = G1Skill1
(Using single LINQ to XML)
I tried this code :
var xmlDoc = XDocument.Load(Server.MapPath("XMLFile1.xml"));
var skills =
from skill in xmlDoc.Descendants("Group")
where skill.Attribute("name").Value.Equals("G1") // && skill.Element("SubSkill").Value.Equals("Group")
select new
{
Myskill = skill.Element("Skill").Value,
mytext= skill.Attribute("name").Value,
};
But don't get proper output .
I would use:
var skills = from group in doc.Descendants("Group")
where (string) group.Attribute("name") == "G1"
from subskill in group.Descendants("SubSkill")
where (string) subskill == "G1skill1sub1"
select (string) subskill.Parent.Attribute("name");
That's going by your inputs and expected output:
- Find all matching groups
- Find all matching subskills within those groups
- For each matching subskill, find the name of the parent (skill)
I tried like this and working fine
string input1 = "G1";
string input2 = "G1skill1sub1";
string output =
(from skill in xdoc.Descendants("Skill")
let subskill = skill.Element("SubSkill")
let g = skill.Parent
where g.Name == "Group" && g.Attribute("name").Value == input1
&& subskill != null && subskill.Value == input2
select skill.Attribute("name").Value).FirstOrDefault();
Console.WriteLine(output);
精彩评论