这是一个奇怪的问题。
我通过TCP连接接收XML消息并且接收XML消息完美地工作,我已经测试过,我收到的XML消息是
<command><printreq><![CDATA[Printed text \r\n Second line with {012} code and <LF> code]]></printreq></command>
当我尝试在我的应用程序中解析它时,我得到异常"<command xmlns=''> was not expected."
但是,我已经将所涉及的方法提取到LINQPad来测试它们,并且它在那里工作。那么我有没有看到隐藏的环境?
以下是我的架构的XSD.exe生成代码:
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class command {
private object itemField;
private ItemChoiceType1 itemElementNameField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("printreq", typeof(string))]
[System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemElementName")]
public object Item {
get {
return this.itemField;
}
set {
this.itemField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public ItemChoiceType1 ItemElementName {
get {
return this.itemElementNameField;
}
set {
this.itemElementNameField = value;
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(IncludeInSchema=false)]
public enum ItemChoiceType1 {
/// <remarks/>
printreq,
}
}
这是我用于反序列化字节数组的方法(字节来自UTF8 - 解码字符串):
public static object DeserializeFromXmlBytes(byte[] objectBytes, Type targetType)
{
var readerSettings = new XmlReaderSettings
{
ConformanceLevel = ConformanceLevel.Fragment
};
var serializer = new XmlSerializer(targetType);
using (var memStream = new MemoryStream(objectBytes))
{
var xmlReader = XmlReader.Create(memStream, readerSettings);
return serializer.Deserialize(xmlReader);
}
}
当我在LINQPad中执行此操作时,它可以正常工作:
string xml = "<command><printreq><![CDATA[Printed text \r\n Second line with {012} code and <LF> code]]></printreq></command>";
var b = System.Text.Encoding.UTF8.GetBytes(xml);
var o = DeserializeFromXmlBytes(b, typeof(command));
Console.WriteLine(o); // Outputs what I expect
但是,我的应用程序中的反序列化失败,除了我提到的例外。 有没有我在这里看不到的东西?
当我对根元素进行硬编码时:
var xRoot = new XmlRootAttribute
{
ElementName = "command",
IsNullable = true
};
它解析时没有错误,但命令是错误的。生成的命令具有子元素breakend
(也已指定,但未在此处的代码中列出)而不是printreq
。这变得越来越怪异。
好的,breakend
是列为ItemChoiceType1
的第一种类型,所以它可能尝试做出“最好”的努力吗?
编辑:我终于修复了它,这是一个奇怪的情况,一些编译文件留在内存或其他东西,只是删除并重新创建一些文件,现在它的工作原理。案件结案。