开发者

One to Many Linq to XML query

I have an XML string that looks like this:

<Attributes>
    <ProductAttribute id="1">
        <ProductAttributeValue>
   开发者_如何学Go         <Value>a</Value>
        </ProductAttributeValue>
    </ProductAttribute>
    <ProductAttribute id="2">
        <ProductAttributeValue>
            <Value>a</Value>
        </ProductAttributeValue>
        <ProductAttributeValue>
            <Value>b</Value>
        </ProductAttributeValue>
    </ProductAttribute>    
</Attributes>

I would like to return an IEnumerable like this:

Id Value
1  a
2  a b

I have tried this and only got the "b" value for Id "2":

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

I tried this:

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

But could not cast Value as a string. Using LINQPad the output was like this:

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

I am trying to just return the values. Is this even possible?

Thanks.


If you wanted a contatenated string of those values like "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())
    };


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

Of course, Value will be an IEnumerable<string>.

Edit:

If you want the output to concat the Value elements into one string you can do this:

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

Then the output will be:

Id Value
1  a 
2  a b
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜