Создание настраиваемого компонента конвейера biztalk для преобразования HTML в XML? - PullRequest
2 голосов
/ 29 октября 2011

Я использую BizTalk Server 2006 (R2) и Visual Studio 2005, В моем приложении у меня есть HTML, который должен быть преобразован в XML в настроенном компоненте конвейера Я передаю HTML, как это,

<HTML><Customer><Data><Name>Udaya</Name><Age>18</Age><Nation>India</Nation></Data></Customer></HTML>

Я должен получить как XML, как это

<ns0:Customer xmlns:ns0="http://CWW.com">
    <Data>
        <Name>Udaya</Name>
        <Age>18</Age>
        <Nation>India</Nation>
    </Data>
</ns0:Customer>

Может кто-нибудь подсказать, есть ли другой способ сделать то же самое без использования настроенного конвейера?

Я пытаюсь использовать приведенный ниже компонент конвейера, но он не работает

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.ComponentModel;
using Microsoft.BizTalk.Component.Interop;
using Microsoft.BizTalk.Message.Interop;
//using System.Windows.Forms;
using System.CodeDom;
using HtmlAgilityPack;
namespace MessageBatchPipelineCompoent
{

[ComponentCategory(CategoryTypes.CATID_PipelineComponent)]

[ComponentCategory(CategoryTypes.CATID_DisassemblingParser)]

[System.Runtime.InteropServices.Guid("6118B8F0-8684-4ba2-87B4-8336D70BD4F7")]

public class DisassemblePipeline : IBaseComponent,

IDisassemblerComponent,

IComponentUI,

IPersistPropertyBag
{

    //Used to hold disassembled messages

    private System.Collections.Queue qOutputMsgs = new System.Collections.Queue();

    private string systemPropertiesNamespace = @"http://schemas.microsoft.com/BizTalk/2003/system-properties";

    /// <summary>

    /// Batch size used to batch records

    /// </summary>

    private int _BatchSize;

    public int BatchSize
    {

        get { return _BatchSize; }

        set { _BatchSize = value; }

    }

    /// <summary>

    /// Default constructor

    /// </summary>

    public DisassemblePipeline()
    {

    }

    /// <summary>

    /// Description of pipeline

    /// </summary>

    public string Description
    {

        get
        {

            return "Component to convert HTML to XML";

        }

    }

    /// <summary>

    /// Name of pipeline

    /// </summary>

    public string Name
    {

        get
        {

            return "HTMLToXMLComponent";

        }

    }

    /// <summary>

    /// Pipeline version

    /// </summary>

    public string Version
    {

        get
        {

            return "1.0.0.0";

        }

    }



    /// <summary>

    /// Returns collecton of errors

    /// </summary>

    public System.Collections.IEnumerator Validate(object projectSystem)
    {

        return null;

    }

    /// <summary>

    /// Returns icon of pipeline

    /// </summary>

    public System.IntPtr Icon
    {

        get
        {

            return new System.IntPtr();

        }

    }



    /// <summary>

    /// Class GUID

    /// </summary>

    public void GetClassID(out Guid classID)
    {

        classID = new Guid("ACC3F15A-C389-4a5d-8F8E-2A951CDC4C19");

    }

    /// <summary>

    /// InitNew

    /// </summary>

    public void InitNew()
    {

    }

    /// <summary>

    /// Load property from property bag

    /// </summary>

    public void Load(IPropertyBag propertyBag, int errorLog)
    {

        object val = null;

        try
        {

            propertyBag.Read("BatchSize", out val, 0);

        }
        catch (ArgumentException)
        {

        }
        catch (Exception ex)
        {
            throw new ApplicationException("Error reading PropertyBag: " + ex.Message);
        }
        if (val != null)

            _BatchSize = (int)val;

        else

            _BatchSize = 1;

    }

    /// <summary>

    /// Write property to property bag

    /// </summary>

    public void Save(IPropertyBag propertyBag, bool clearDirty, bool saveAllProperties)
    {

        object val = (object)BatchSize;

        propertyBag.Write("BatchSize", ref val);

    }

    /// <summary>

    /// Disassembles (breaks) message into small messages as per batch size

    /// </summary>

    public void Disassemble(IPipelineContext pContext, IBaseMessage pInMsg)
    {

        string originalDataString;

        try
        {

            //fetch original message

            Stream originalMessageStream = pInMsg.BodyPart.GetOriginalDataStream();

            byte[] bufferOriginalMessage = new byte[originalMessageStream.Length];

            originalMessageStream.Read(bufferOriginalMessage, 0, Convert.ToInt32(originalMessageStream.Length));

            originalDataString = System.Text.ASCIIEncoding.ASCII.GetString(bufferOriginalMessage);

        }

        catch (Exception ex)
        {

            throw new ApplicationException("Error in reading original message: " + ex.Message);

        }

       //XmlDocument originalMessageDoc = new XmlDocument();

        //HtmlDocument originalMessageDoc = new HtmlDocument();

        HtmlAgilityPack.HtmlDocument originalMessageDoc = new HtmlAgilityPack.HtmlDocument();

        originalMessageDoc.Load(originalDataString);

        StringBuilder messageString;

        try
        {

            //load original message

           // HtmlNode.

           // originalMessageDoc.GetElementsByTagName("HTML");

           //originalMessageDoc.DocumentElement.FirstChild.RemoveChild(originalMessageDoc.DocumentElement.FirstChild);

           // originalMessageDoc.DocumentElement.FirstChild.Attributes.Append("ns0");

           // String RootElement = originalMessageDoc.DocumentElement.Name;

            messageString = new StringBuilder();

            String RootNode = originalMessageDoc.DocumentNode.Name;

            System.Diagnostics.EventLog.WriteEntry("Hello", "What doing");

            //originalMessageDoc.DocumentNode.Attributes(RootNode,ns0);

            //messageString.Insert();

            messageString.Append(true);

           // messageString.Append("<" + RootNode + " xmlns:ns0='" + "http://SomeContent" + "'>");

            //messageString.Append("</" + "Sample" + ">");

            CreateOutgoingMessage(pContext, messageString.ToString(), "http://SomeContent", "Sample", pInMsg);

        }

        catch (Exception ex)
        {

            throw new ApplicationException("Error in writing outgoing messages: " + ex.Message);

        }

        finally
        {

            messageString = null;

            originalMessageDoc = null;

        }

    }

    /// <summary>

    /// Used to pass output messages`to next stage

    /// </summary>

    public IBaseMessage GetNext(IPipelineContext pContext)
    {

        if (qOutputMsgs.Count > 0)

            return (IBaseMessage)qOutputMsgs.Dequeue();

        else

            return null;

    }

    /// <summary>

    /// Queue outgoing messages

    /// </summary>

    private void CreateOutgoingMessage(IPipelineContext pContext, String messageString, string namespaceURI, string rootElement, IBaseMessage pInMsg)
    {

        IBaseMessage outMsg;

        try
        {

            //create outgoing message

            outMsg = pContext.GetMessageFactory().CreateMessage();

            outMsg.Context = pInMsg.Context;

            outMsg.AddPart("Body", pContext.GetMessageFactory().CreateMessagePart(), true);

            outMsg.Context.Promote("MessageType", systemPropertiesNamespace,"Sample");

           // outMsg.Context.Promote("MessageType", systemPropertiesNamespace, "http://SomeText" + "#" + rootElement.Replace("ns0:", ""));

            byte[] bufferOoutgoingMessage = System.Text.ASCIIEncoding.ASCII.GetBytes(messageString);

            outMsg.BodyPart.Data = new MemoryStream(bufferOoutgoingMessage);

            qOutputMsgs.Enqueue(outMsg);



        }

        catch (Exception ex)
        {

            throw new ApplicationException("Error in queueing outgoing messages: " + ex.Message);

        }

    }



   }

}

Это компонент, который я создал, но он не работает.

Теперь у меня ошибка как недопустимые символы в пути.

1 Ответ

0 голосов
/ 03 ноября 2011

ранее я использовал originalMessageDoc.Load (originalDataString); в функции дизассемблирования, поэтому я получал недопустимые символы в ошибке пути. Теперь я решил эту конкретную проблему, заменив ее на

originalMessageDoc.LoadHTML(originalDataString);

Теперь я могу видеть в журнале событий, что я создал мой xml, но все же у меня есть небольшая ошибка когда String RootNode = originalMessageDoc.DocumentNode.Name;

Раньше я давал вот так, а теперь жестко болел теперь он говорит, что rootnode не объявлен

...