You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中XML文档(0,0)错误:ObjectEventType反序列化失败求助

Fixing Your XML Deserialization Error (0, 0)

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 filePath points to the correct XML file with valid content
  • Verify that your EPCISDocumentType and related classes (like ObjectEventType, 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")] for EPCISDocumentType)

内容的提问来源于stack exchange,提问作者Ngoc Duy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:37:47