LINQ to XML merges with idref

I have an XML structure such as:

[...] <Fruits> <Fruit> <Specification>id_1001_0</Specification> <Weight>23</Weight> </Fruit> </Fruits> <FruitSpecification id="id_1001_0"> <Type>Apple</Type> </FruitSpecification> [...] 

I want to use Linq for XML to read this in (non-anonymous) objects. Let's say I have the following code:

 var fruits = from xele in xDoc.Root.Element("Fruits").Elements("Fruit") select new Fruit() { Weight = xele.Element("Weight").Value } 

How can I expand a query to join the correct FruitSpecification tag? The goal is to write this:

 var fruits = from xele in xDoc.Root.Element("Fruits").Elements("Fruit") //some join? select new Fruit() { Weight = xele.Element("Weight").Value, Type = xjoinedelement.Element("Type").Value } 

Hope this is understandable, I made this β€œfruit” sample, my actual XML is much more complicated ...

+4
source share
2 answers

Yes, a simple connection will do the trick:

 var fruits = from f in xdoc.Root.Element("Fruits").Elements("Fruit") join fs in xdoc.Root.Elements("FruitSpecification") on (string)f.Element("Specification") equals (string)fs.Attribute("id") select new Fruit() { Weight = (int)f.Element("Weight"), Type = (string)fs.Element("Type") }; 

Definition of a class of fruit:

 public class Fruit { public int Weight { get; set; } public string Type { get; set; } } 
+4
source

Try the following:

 class Fruit { public int Weight { get; set; } public string Type { get; set; } } string xml = @" <root> <Fruits> <Fruit> <Specification>id_1001_0</Specification> <Weight>23</Weight> </Fruit> <Fruit> <Specification>id_1002_0</Specification> <Weight>25</Weight> </Fruit> </Fruits> <FruitSpecification id='id_1001_0'> <Type>Apple</Type> </FruitSpecification> <FruitSpecification id='id_1002_0'> <Type>Orange</Type> </FruitSpecification> </root>"; XElement element = XElement.Parse(xml); IEnumerable<XElement> xFruites = element.Descendants("Fruit"); IEnumerable<XElement> xFruitSpecifications = element.Descendants("FruitSpecification"); IEnumerable<Fruit> frits = xFruites.Join( xFruitSpecifications, f => f.Element("Specification").Value, s => s.Attribute("id").Value, (f, s) => new Fruit { Type = s.Element("Type").Value, Weight = int.Parse(f.Element("Weight").Value) }); 
+1
source

All Articles