I have some ugly xml(if I could change I would) coming to me that I need to be able to process. I wanted to group by a specific attribute in the XML for further processing. The problem is that some of the attributes have a type=”A” and some have type=”A1″, type=”A2″, etc. I want all of the elements that have an attribute type value that starts with “A” be grouped together.
This is not working and I don’t know what to change to get it to work:
var result = from ele in xdoc.Descendants(Namespace + "item")
let item= ele.Attribute("type").Value.Substring(1,1)
group ele by item into grp
select grp;
When I take off the substring it works fine, but obviously doesn’t group how I want.
Error:
Error has been thrown by the target of an invocation
Example XML:
<items>
<item type="A" position="0">
<itemvalue>10</itemvalue>
</item>
<item type="A1" position="1">
<itemvalue>20</itemvalue>
</item>
<item type="A2" position="2">
<itemvalue>30</itemvalue>
</item>
<item type="B" position="0">
<itemvalue>10</itemvalue>
</item>
<item type="B1" position="1">
<itemvalue>20</itemvalue>
</item>
<item type="B2" position="2">
<itemvalue>30</itemvalue>
</item>
</items>
Without a compiler at my disposal and typing this on my mobile I would say that you should pass 0 as the first argument to
Substring, i.e.Substring(0,1).