How to add an attribute to an XML with a count of that element with an element
The xml has a number of NEWRECORDS that has some normal elements, followed by elements with elements in them. The elements that have subelements can occur anywhere from 0 to infinity and need to receive an attribute called count which has the occurences within the NEWRECORD. now i found out you can do a count on an element id and you can use linq to state to do it starting from a certain layer, but none of these elements are required and there are about 15 of them, would that mean searching 15 times? Or is there an easy way to add a count to the xml?
i have added the xml but cut out alot of information to keep it readable. in short, NAME and YEAR are elements not needing a count, since they are unique for the NEWRECORD and have no subelements (and are required). The others need a count attribute (and will have subelements) even if there is only 1 and could even be missing.
<NEWFILE>
<NEWRECORD num="343">
<NAME>Single Scheme</NAME>
<YEAR>2005</YEAR>
<SPS></SPS>
<SPS></SPS>
<SPS></SPS>
<SPS></SPS>
<SPS></SPS>
<MODULATION_2005></MODULATION_2005>
<MODULATION_2005></MODULATION_2005>
<MODULATION_2005></MODULATION_2005>
<ADDITIONAL></ADDITIONAL>
<NOTES></NOTES>
<PART_C2_HISTORY></PART_C2_HISTORY>
<PART_C2_HISTORY></PART_C2_HISTORY>
<PART_C2_HISTORY></PART_C2_HISTORY>
<PART_C2_HISTORY></PART_C2_HISTORY>
<PART_C2_HISTORY></PART_C2_HISTORY>
<PART_C2_HISTORY></PART_C2_HISTORY>
<PART_C2_HISTORY></PART_C2_HISTORY>
</NEWRECORD>
<NEWRECORD num="344">
<NAME>Single Scheme</NAME>
<YEAR>2005</YEAR>
<SPS></SPS>
<SPS></SPS>
<MODULATION_2005></MODULATION_2005>
<ADDITIONAL></ADDITIONAL>
<PART_C2_HISTORY><开发者_Go百科/PART_C2_HISTORY>
<PART_C2_HISTORY></PART_C2_HISTORY>
<PART_C2_HISTORY></PART_C2_HISTORY>
</NEWRECORD>
</NEWFILE>
With some trial and error and use of various LINQ i made a method. considering i am a LINQ newbie and i nearly found no info on what i did (i got some help from here), i am quite happy with the outcome and tought it might be usefull to others. Also are there any enhancements i could make to this?
public XDocument FormatcountPreProcData(XDocument inputDoc)
{
if (inputDoc != null)
{
var elementsToChange = inputDoc.Elements("NEWFILE").Elements("NEWRECORD").Elements();
foreach (var element in elementsToChange)
{
if (element.Descendants().Any())
{
Int32 count = inputDoc.Elements("NEWFILE").Elements("NEWRECORD").Elements(element.Name.ToString()).Count();
element.Add(new XAttribute("count", count));
}
}
}
return inputDoc;
}
精彩评论