2010-08-27 83 views
1

我有一个看起来像这样的XML字符串:一对多的LINQ to XML查询

<Attributes> 
    <ProductAttribute id="1"> 
     <ProductAttributeValue> 
      <Value>a</Value> 
     </ProductAttributeValue> 
    </ProductAttribute> 
    <ProductAttribute id="2"> 
     <ProductAttributeValue> 
      <Value>a</Value> 
     </ProductAttributeValue> 
     <ProductAttributeValue> 
      <Value>b</Value> 
     </ProductAttributeValue> 
    </ProductAttribute>  
</Attributes> 

我想返回一个IEnumerable这样的:

Id Value 
1 a 
2 a b 

我已经尝试这样做,只得到了ID为 “2” 的 “b” 值:

XElement e = XElement.Parse(xmlString); 
var q = from pa in e.Elements("ProductAttribute") 
from pav in pa.Elements("ProductAttributeValue").Elements("Value") 
select new 
{ 
Id = (int)pa.Attribute("id"), 
Value = (string)pav 
}; 

我尝试这样做:

XElement e = XElement.Parse(xmlString); 
    var q = from pa in e.Elements("ProductAttribute") 
    select new 
    { 
    Id = (int)pa.Attribute("id"), 
    Value = pa.Elements("ProductAttributeValue").Elements("Value") 
    }; 

但无法将值作为字符串进行转换。使用LINQPad的输出是这样的:

Id Value 
1 a 
2 <Value>a</Value> 
    <Value>b</Value> 

我想只是返回值。这甚至有可能吗?

谢谢。

回答

1

如果你想这些值的contatenated串像"a b"

XElement e = XElement.Parse(xmlString); 
    var q = from pa in e.Elements("ProductAttribute") 
    select new 
    { 
    Id = (int)pa.Attribute("id"), 
    Value = string.Join(" " , 
        pa.Elements("ProductAttributeValue") 
        .Elements("Value")            
        .Select(x=>x.Value) 
        .ToArray()) 
    }; 
+0

这也非常有帮助!谢谢坎贝尔。仅供参考,代码示例中缺少一个右括号。除此之外,它完美的工作。 – trevorc 2010-08-27 01:28:53

+0

@joebloe:谢谢关于paren的说明。记得投票(当你有足够的代表)并选择一个'接受的答案'作为StackOverflow声誉系统的一部分。为那些花时间回答问题的人提供声誉。我投了你的问题,因为我认为这是一个很好的问题,并帮助你找到一些代表。 – 2010-08-27 02:07:26

1
XElement e = XElement.Parse(xmlString); 
var q = from pa in e.Elements("ProductAttribute") 
select new 
{ 
Id = (int)pa.Attribute("id"), 
Value = from pav in pa.Elements("ProductAttributeValue").Elements("Value") select pav.Value 
}; 

当然,值将是一个IEnumerable<string>

编辑:

如果你想输出到Concat的价值元素连接成一个字符串,你可以这样做:

XElement e = XElement.Parse(xmlString); 
var q = from pa in e.Elements("ProductAttribute") 
select new 
{ 
Id = (int)pa.Attribute("id"), 
Value = string.Join(" ", (from pav in pa.Elements("ProductAttributeValue").Elements("Value") 
     select pav.Value).ToArray()) 
}; 

然后输出将是:

Id Value 
1 a 
2 a b 
+0

就是这样!我用'in'尝试了一些变体,但无法获得正确的语法。感谢Richard。 – trevorc 2010-08-27 01:20:34

+0

欢迎您... – 2010-08-27 01:24:49