在自定义管道组件中检查收到的文档是XML还是Edifact

时间:2018-12-20 11:21:37

标签: c# xml biztalk edifact

问题:我需要检查XML元素内的传入文档是XML还是Edifact格式。根据文档的格式,需要对其进行相应的处理。

当前解决方案:根据传入的消息创建一个XDocument实例。传入消息始终为XML。

var originalStream = pInMsg.BodyPart.GetOriginalDataStream();
                        XDocument xDoc;
                        using (XmlReader reader = XmlReader.Create(originalStream))
                        {
                            reader.MoveToContent();
                            xDoc = XDocument.Load(reader);
                        }

此后,从XML元素“ msgbody”中提取文档。当前,它假定此格式为XML格式,当文档为Edifact格式时会引发错误。下面的代码将其提取,并创建一个新的XDocument,并将其发送到MessageBox。

string extractedDocument = xDoc.Root.Element("msgbody").Value;
extractedDocument = HttpUtility.HtmlDecode(extractedDocument);
XDocument outputXml = XDocument.Parse(extractedDocument);

来自biztalk的示例消息

<NewTable>
  <conversationID>2ff845e7-30a4-482e-98d6-8c3249c5dea1</conversationID>
  <hostUTC>2018-12-17T12:17:04.107Z</hostUTC>
  <msgType>INVOIC</msgType>
  <msgid>721254</msgid>
  <icref>36655</icref>
  <msgFormat_org>EDIFACTBauhaus</msgFormat_org>
  <msgFormat>EDI</msgFormat>
  <msgbody>"Edifact or XML document"</msgbody>
  <fromID>GLN:5790034516518</fromID>
  <toID>GLN:5790000451485</toID>
</NewTable>

问题:在处理文档之前,如何在msgbody标记内为文档创建检查,以确定它是XML格式还是Edifact格式?

1 个答案:

答案 0 :(得分:0)

我喜欢使用字典来使用xml linq获取所有属性。请参见下面的代码。如果您要获取字符串响应,请使用Parse(string)代替nuse(文件名)方法。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication93
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {

            XDocument doc = XDocument.Load(FILENAME);
            Dictionary<string, string> dict = doc.Descendants("NewTable").Elements()
                .GroupBy(x => x.Name.LocalName, y => (string)y)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());

        }

    }


}