0

问题:我需要检查 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 格式,然后再处理它?

4

1 回答 1

0

我喜欢使用字典来使用 xml linq 获取所有属性。请参阅下面的代码。如果您收到字符串响应,则使用 Nuse 而不是 Load(filename) 方法使用 Parse(string)。

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());

        }

    }


}
于 2018-12-20T11:43:58.830 回答