Linq to XML Get parent element attribute value by querying it's children
-
25-05-2021 - |
Question
I'm trying to build a Linq to XML Query but havent found a real solution yet.
Here is my XML
<Nodes>
<Node Text="Map" Value="Map">
<Node Text="12YD" Value="12YD">
<Node Text="PType" Value="PType">
<Node Text="12" Value="12" />
</Node>
<Node Text="SType" Value="SType">
<Node Text="2" Value="2" />
</Node>
</Node>
<Node Text="12YP" Value="12YP">
<Node Text="PType" Value="PType">
<Node Text="12" Value="12" />
</Node>
<Node Text="SType" Value="SType">
<Node Text="1" Value="1" />
</Node>
</Node>
</Node>
</Nodes>
The parameters I have available are for the PType node and the SType node, now depending on their values I need to get the Parent Node Attribute Value.
Example:
Params: {PType:12}, {SType:2} should give me 12YD as a result.
Params: {PType:12}, {SType:1} should give me 12YP as a result.
I have tried different solutions even using PredicateBuilder but without success. Any help would be appreciated.
Here's the latest code I have using LinqPad.
void Main()
{
var xml = XElement.Load (@"C:\map.xml");
string value = "{PType:12},{SType:1}";
string[] mapReqValues = value.Split(',');
var predicate = PredicateBuilder.False<XElement>();
foreach (string r in mapReqValues)
{
var m = Regex.Match(r, @"{([^}]+)}").Groups[1].Value.Split(':');
predicate = predicate.Or(p => p.Attribute("Value").Value == m[0] &&
p.Descendants().Attributes("Value").FirstOrDefault().Value == m[1]);
}
var result = xml.Descendants().AsQueryable().Where(predicate);
result.Dump();
}
La solution
XDocument xDoc = XDocument.Load(new StringReader(xml));
var Tuples = xDoc.Descendants("Node").Where(n => n.Attribute("Text").Value == "PType")
.Join(
xDoc.Descendants("Node").Where(n => n.Attribute("Text").Value == "SType"),
n1 => n1.Parent,
n2 => n2.Parent,
(n1, n2) => new
{
ParentsValue = n1.Parent.Attribute("Text").Value,
PValue = n1.Element("Node").Attribute("Text").Value,
SValue = n2.Element("Node").Attribute("Text").Value
}
);
var result = Tuples.Where(n => n.PValue == "12" && n.SValue == "1")
.Select(n => n.ParentsValue)
.ToArray();
Autres conseils
In dealing with XML XPath is your friend...
For PType 12, Stype 1
var result = xml.XPathSelectElements(@"//Node[Node[@Value='PType']/Node[@Value='12'] and Node[@Value='SType']/Node[@Value='1']]");
That's a bit of a mouthful...
//Node
Every node anywhere in the tree
[Node[@Value='PType']
That has a child node of type Node with an attribute Value that has the value (!) PType
/Node[@Value='12']
That has a child node of the type Node with a Value attribute with a value of 12
and also all the stuff to get to SType 1
You can filter the heck out of XML with XPath and it will let you search for descendants that match a pattern - its what its geared for.
So if you replace the string above with a string.format then you'd be away and running...