XSD生成的可序列化复杂对象XML序列化时数组类型转换异常求助
Hey there, that serialization error is definitely coming from how you're constructing the Body property's nested arrays. Let's break this down step by step:
The Root Cause: Mismatched XML Hierarchy and Class Structure
Looking at your sample XML, the Body section follows this hierarchy:
<body> <journal> <journal_metadata>...</journal_metadata> </journal> </body>
The XSD-generated classes mirror this structure, which means:
DoiBatch.Bodyis an array ofDoiBatchBodyobjects- Each
DoiBatchBodycontains an array ofJournalobjects - Each
Journalcontains an array ofJournalMetadataobjects (yourdoiBodyvariable)
Your original code doiBatch.Body = new[] { new[]{ new []{doiBody}}}; creates a 3-layer array of JournalMetadata directly, which doesn't match the class structure at all—hence the type conversion errors.
Fixed Code: Build the Hierarchy Correctly
Update the #region Body section of your Create method to construct the objects in the right order:
#region Body // Create your JournalMetadata object as before DoiBatchBodyJournalJournalMetadata doiBody = new DoiBatchBodyJournalJournalMetadata(); DoiBatchBodyJournalJournalMetadataDoiData doiBodyData = new DoiBatchBodyJournalJournalMetadataDoiData(); doiBodyData.Doi = jPost.DoiPrefix + jPost.RefNum; doiBodyData.Resource = jPost.BaseUrl + @"?refnum=" + jPost.RefNum; doiBody.DoiData = new[] { doiBodyData }; doiBody.FullTitle = jPost.Title; doiBody.AbbrevTitle = jPost.Title.Substring(0, 10); //truncate title. doiBody.Language = "EN"; // 1. Wrap JournalMetadata in an array and assign to a Journal object var journal = new DoiBatchBodyJournal(); journal.JournalMetadata = new[] { doiBody }; // 2. Wrap the Journal in an array and assign to a DoiBatchBody object var batchBody = new DoiBatchBody(); batchBody.Journal = new[] { journal }; // 3. Finally, wrap the DoiBatchBody in an array for the DoiBatch.Body property doiBatch.Body = new[] { batchBody }; #endregion
Bonus Fix: Incorrect Timestamp Format
I noticed you're generating the timestamp with DateTime.Now.ToOADate().ToString(CultureInfo.InvariantCulture)—this won't produce the format Crossref expects. They require a timestamp in YYYYMMDDHHMMSS format (like the sample's 20190430133609), so update that line to:
doiHead.Timestamp = DateTime.Now.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture);
With these changes, your serialization should work without throwing type errors, and your timestamp will be compliant with Crossref's requirements.
内容的提问来源于stack exchange,提问作者Richard Barnes

