LINQ to XML与idref连接

时间:2013-01-30 09:25:05

标签: c# .net xml linq-to-xml

我有类似以下的XML结构:

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

我想使用Linq to XML将其读入(非匿名)对象。 假设我有以下代码:

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

如何扩展查询以加入正确的FruitSpecification标记? 目标是能够写下这个:

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
             }

我希望这是可以理解的,我做了这个“水果”样本,我的实际XML更加复杂......

2 个答案:

答案 0 :(得分:4)

是的,简单的加入就可以解决问题:

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")
    };

水果类定义:

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

答案 1 :(得分:1)

试试这个:

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)
        });