When you use the Interchange object to create the X12 from scratch the appropriate trailing segments will be created with matching control numbers and the segment counts, transaction counts, functional group counts will all be dynamically calculated with
you serialize to x12.
The behaviour is slightly different when you parse a file or deserialize the file, because we want to capture the X12 as-is even if the sender sent an invalid file.
In the scenario you are describing, I am assuming you have added or removed some segments via the XML and then transformed back into X12.
Since the TransformToX12 method does not pass through the Interchange object, it is only doing a literal transform of your XML, this will not have the counts corrected. If you then run the resulting X12 back through the parser into the Interchange
object and then serializeToX12 again, than the counts will be corrected.
I am assuming the same issue might be happening with the control numbers. If you are modify the XML's control numbers you would need to do it for both the header segment and the trailing segment, since this would only be done for you if you created
it through the Interchange object.
I have added a unit test at
which parses an X12 into XML, loads the XML into an XmlDocument and removes a segment, than Transforms it back into X12. It then runs the X12 back through the parser and serializes to correct the segment counts.
Let me know if this solves your problem.