我正在尝试通过EdiFabric购买的EdiFabric.Definitions.X12_004010_855类建立EDI 855文件。我遇到问题,尝试将此对象转换为有效的EDI 855文件。这就是我正在做的事情:
创建新的M_855对象:
var m_855 = new M_855();
m_855.S_ST = new EdiFabric.Definitions.X12_004010_855.S_ST();
m_855.S_ST.D_329_2 = "Stuff...";
m_855.S_ST.D_143_1 = EdiFabric.Definitions.X12_004010_855.S_STD_143_1.Item855;
m_855.S_BAK = new EdiFabric.Definitions.X12_004010_855.S_BAK();
....more code, but removed for brevity...
将对象序列化为XML
var xml = Serialize<M_855>(m_855, "www.edifabric.com/x12")
var interchange = Interchange.LoadFrom(xml); //blows up here
public static XElement Serialize<T>(T instance, string nameSpace)
{
// Fix: using instance.GetType() instead of typeof(T)
var serializer = new XmlSerializer(instance.GetType(), nameSpace);
using (var ms = new MemoryStream())
{
serializer.Serialize(ms, instance);
ms.Position = 0;
return XElement.Load(ms, LoadOptions.PreserveWhitespace);
}
}
这给了我这个有效的XML:
<M_855 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="www.edifabric.com/x12">
<S_ST>
<D_143_1>855</D_143_1>
<D_329_2>1126</D_329_2>
</S_ST>
<S_BAK>
<D_353_1>06</D_353_1>
<D_587_2>AD</D_587_2>
<D_324_3>TEST3</D_324_3>
<D_373_4>20160902</D_373_4>
</S_BAK>
<G_N1>
<S_N1>
<D_98_1>ST</D_98_1>
<D_93_2>Name here</D_93_2>
</S_N1>
</G_N1>
<G_PO1>
<S_PO1>
<D_350_1>001</D_350_1>
<D_330_2>1</D_330_2>
<D_212_4>344.35</D_212_4>
<D_234_7>10038</D_234_7>
<D_234_9>0135010038</D_234_9>
</S_PO1>
<G_ACK>
<S_ACK>
<D_668_1>AC</D_668_1>
</S_ACK>
</G_ACK>
</G_PO1>
<G_CTT>
<S_CTT>
<D_354_1>1</D_354_1>
</S_CTT>
</G_CTT>
<S_SE>
<D_96_1>6</D_96_1>
<D_329_2>1126</D_329_2>
</S_SE>
</M_855>
调用LoadFrom() var interchange = Interchange.LoadFrom(xml)
错误
InnerException: {"<M_855 xmlns='www.edifabric.com/x12'> was not expected."}
Message: "There is an error in XML document (0, 0)."
这是应该怎么做的?我还尝试创建一个新的Interchange()对象并将XML作为Message.Item附加,但是收到相同的错误消息。
答案 0 :(得分:0)
在这一行: var xml = Serialize(m_855,&#34; TestNameSpace&#34;)
命名空间实际上应该是www.edifabric.com/x12'。不允许序列化到自定义命名空间。
答案 1 :(得分:0)
因此,经过多次挫折,我得到了它的工作。我原帖中的XML结构不完整。上面的M_855节点只是我需要传递到Interchange.LoadFrom()方法的XML的一部分。
正确的结构需要是一个完整的X12包络,从INTERCHANGE节点开始。
<INTERCHANGE xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="www.edifabric.com/x12">
<S_ISA>
...
</S_ISA>
<GROUPS>
<GROUP>
<S_GS>
...
</S_GS>
<MESSAGES>
<MESSAGE>
<Item>
<M_855>
...
</M_855>
</Item>
<Context>
<Tag>855</Tag>
<Version>004010</Version>
<Format>X12</Format>
</Context>
</MESSAGE>
</MESSAGES>
<S_GE>
...
</S_GE>
</GROUP>
</GROUPS>
<S_IEA>
...
</S_IEA>
</INTERCHANGE>
所以现在不是序列化M_855对象,而是这样做:
var interchange855 = new Interchange();
interchange855.Isa = new S_ISA()
{
...
}
interchange855.Groups.Add(new Group());
interchange855.Iea = new S_IEA()
{
...
}
var edi = interchange855.ToEdi(); //works!