Xml阅读问题。
private DataPDU Deserialize(string filepath)
{
XmlSerializer deserializer = new XmlSerializer(typeof(DataPDU));
UTF8Encoding utf8 = new UTF8Encoding(true);
StreamReader reader = new StreamReader(filepath, utf8);
object obj = deserializer.Deserialize(reader); //error raising here
DataPDU XmlData = (DataPDU)obj;
reader.Close();
return XmlData;
}
如果我删除" Saa:"从标签我的代码工作正常。但文件提供者以上述格式提供in文件。你能帮忙吗?部分错误跟踪吼叫。
System.InvalidOperationException was unhandled
HResult=-2146233079
Message=There is an error in XML document (2, 6).
Source=System.Xml
StackTrace:
Message=<DataPDU xmlns='urn:swift:saa:xsd:saa.2.0'> was not expected.
Source=Microsoft.GeneratedCode
StackTrace:
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderDataPDU.Read9_DataPDU()
InnerException:
xml文件样本:
<?xml version="1.0" encoding="UTF-8"?>
<Saa:DataPDU xmlns:Saa="urn:swift:saa:xsd:saa.2.0" xmlns:Sw="urn:swift:snl:ns.Sw" xmlns:SwGbl="urn:swift:snl:ns.SwGbl" xmlns:SwInt="urn:swift:snl:ns.SwInt" xmlns:SwSec="urn:swift:snl:ns.SwSec">
<Saa:Body>
<AppHdr:AppHdr xmlns="urn:iso:std:iso:20022:tech:xsd:head.001.001.01" xmlns:AppHdr="urn:iso:std:iso:20022:tech:xsd:head.001.001.01">
<Fr>
<FIId>
<FinInstnId>
<BICFI>ABBLBDDH</BICFI>
</FinInstnId>
</FIId>
</Fr>
<To>
<FIId>
<FinInstnId>
<BICFI>BBHOBDDHRTG</BICFI>
</FinInstnId>
</FIId>
</To>
<BizMsgIdr>MRQ140527142125236</BizMsgIdr>
<MsgDefIdr>pacs.008.001.04</MsgDefIdr>
<BizSvc>RTGS_CSCT</BizSvc>
<CreDt>2014-05-27T14:21:25</CreDt>
</AppHdr:AppHdr>
</Saa:Body>
</Saa:DataPDU>
答案 0 :(得分:0)
上周我用同样的解决方案帮助了某人。使用Regex删除命名空间
public DataPDU Deserialize(string filepath)
{
XmlSerializer deserializer = new XmlSerializer(typeof(DataPDU));
UTF8Encoding utf8 = new UTF8Encoding(true);
StreamReader reader = new StreamReader(filepath, utf8);
string text = reader.ReadToEnd();
string pattern = "(</?)(\\w+:)";
string fixedText = Regex.Replace(text,pattern,"$1");
StringReader fixedReader = new StringReader(fixedText);
object obj = deserializer.Deserialize(fixedReader); //error raising here
DataPDU XmlData = (DataPDU)obj;
reader.Close();
return XmlData;
}