Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# XML反序列化-索引和长度必须引用字符串中的位置_C#_Xml_Visual Studio - Fatal编程技术网

C# XML反序列化-索引和长度必须引用字符串中的位置

C# XML反序列化-索引和长度必须引用字符串中的位置,c#,xml,visual-studio,C#,Xml,Visual Studio,我正在尝试反序列化一个XML文件,但收到一个错误,该错误显示: System.InvalidOperationException: There is an error in XML document (200, 67). ---> System.ArgumentOutOfRangeException: Index and length must refer to a location within the string. Parameter name: length 我正在使用此代码对文

我正在尝试反序列化一个XML文件,但收到一个错误,该错误显示:

System.InvalidOperationException: There is an error in XML document (200, 67). ---> System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.
Parameter name: length
我正在使用此代码对文档进行反序列化

public static object DeserializeFromXmlFile(FileInfo srcFile, Type type)
{
  XmlSerializer xmlSerializer = new XmlSerializer(type);
  using (XmlReader reader = XmlReader.Create(srcFile.FullName))
  {
    return xmlSerializer.Deserialize(reader);
  }
}
它总是在同一行上失败-这个例子只有63个字符长,但它前面有两个制表符,所以我猜这使得这行有66个字符长,反序列化程序试图从这行读取67个字符

<printorder_delivery_location>FOB</printorder_delivery_location>
离岸价 所有故障行的共同点是
标记的值小于10个字符。如果我添加额外的字符(即使只是空白),它也可以正常工作

<printorder_delivery_location>FOB Hong Kong</printorder_delivery_location>
代码>香港离岸价 我将Notepad++设置为显示隐藏字符,并且
行似乎没有任何问题

如您所见,也有比
行短的行,但这些不会导致反序列化程序失败


有什么我可以检查的来解决这个问题吗?

我一报告这个问题就发现了问题所在

我反序列化到的对象使用
Substring()
方法将
缩短为10个字符。在长度小于10个字符的情况下,这是失败的,因为很明显,索引超出了范围

我所要做的就是在尝试获取子字符串之前,添加一个检查来验证传递位置的长度是否大于10个字符

[XmlElement("printorder_delivery_location")]
public string DeliveryLocation
{
  get => deliveryLocation;
  set
  {
    if (value.Length > 10)
      deliveryLocation = value.Substring(0,10).ToUpper();
    else 
      deliveryLocation = value.ToUpper();
  }
}

您没有显示反序列化所需的模型类。那里有定制的序列化代码吗?是的,有@Dbuggy-我已经发布了一个答案。我犯了一个愚蠢的错误。看起来它没有通过模式检查。必须有一个很好的理由,架构需要10个字符。