4

我有一个如下的 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 要复杂得多......

4

2 回答 2

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; }
}
于 2013-01-30T09:59:47.510 回答
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)
        });
于 2013-01-30T09:49:24.050 回答