我有一个看起来像这样的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>
我想只是返回值。这甚至有可能吗?
谢谢。
这也非常有帮助!谢谢坎贝尔。仅供参考,代码示例中缺少一个右括号。除此之外,它完美的工作。 – trevorc 2010-08-27 01:28:53
@joebloe:谢谢关于paren的说明。记得投票(当你有足够的代表)并选择一个'接受的答案'作为StackOverflow声誉系统的一部分。为那些花时间回答问题的人提供声誉。我投了你的问题,因为我认为这是一个很好的问题,并帮助你找到一些代表。 – 2010-08-27 02:07:26