C#中XML文档(0,0)错误:ObjectEventType反序列化失败求助
Let's break down the critical issues causing your error—there are a few straightforward fixes here:
1. You're trying to deserialize an empty file
First off, your code includes this line:
File.WriteAllText(filePath, "");
This completely clears the XML file you're about to read! When StreamReader tries to parse an empty file, the XML serializer throws the (0, 0) error because there's no XML content to process.
Fix: Delete this line entirely. You only want to read the existing XML file, not overwrite it with empty content.
2. Your XML root node doesn't match the deserialization type
Your XML file's root element is <epcis:EPCISDocument>, but you're trying to deserialize directly to ObjectEventType:
XmlSerializer xmlSerializer = new XmlSerializer(typeof(ObjectEventType));
The serializer expects the root node to match the type you're deserializing to—this mismatch would cause an error even if the file wasn't empty.
Fix: Deserialize the entire EPCISDocumentType first, then extract the ObjectEventType from it:
using (StreamReader reader = new StreamReader(filePath)) { // Serialize the full EPCIS document instead of just ObjectEventType XmlSerializer xmlSerializer = new XmlSerializer(typeof(EPCISDocumentType)); EPCISDocumentType epcisDoc = (EPCISDocumentType)xmlSerializer.Deserialize(reader); // Get the ObjectEventType from the event list ObjectEventType objectEventType = epcisDoc.EPCISBody.EventList .OfType<ObjectEventType>() .FirstOrDefault(); if (objectEventType == null) { throw new InvalidOperationException("No ObjectEventType found in the XML document."); } // Proceed with your existing modifications objectEventType.epcList = epcList.ToArray(); objectEventType.eventTime = DateTime.Now; objectEventType.eventTimeZoneOffset = DateTime.Now.ToString("zzz"); // ... rest of your code ... }
3. Fix XML tag mismatches in your file
Your XML has invalid tag closures that will also break parsing:
<cbvmda:itemExpirationDate>2015-03-15</example:expiry> <cbvmda:lot>A123</example:lot>
The end tags don't match the start tags. Correct them to:
<cbvmda:itemExpirationDate>2015-03-15</cbvmda:itemExpirationDate> <cbvmda:lot>A123</cbvmda:lot>
Final Checks
- Ensure the
filePathpoints to the correct XML file with valid content - Verify that your
EPCISDocumentTypeand related classes (likeObjectEventType,EPCISBodyType) are properly decorated with XML serialization attributes that match the XML's namespaces and element names (e.g.,[XmlRoot(Namespace = "urn:epcglobal:epcis:xsd:1")]forEPCISDocumentType)
内容的提问来源于stack exchange,提问作者Ngoc Duy

