如何自己实现一个丝滑的流程图绘制工具(五)bpmn的xml和json互转

背景

因为服务端给的数据并不是xml,而且服务端要拿的数据是json,所以我们只能xml和json互转,来完成和服务端的对接

xml转json
import XML from './config/jsonxml.js'/*** xml转为json* @param {*} xml*/xmlToJson(xml) {const xotree = new XML.ObjTree()const jsonData = xotree.parseXML(xml)return jsonData},

jsonxml.js

const XML = function() {}//  constructorXML.ObjTree = function() {return this
}//  class variablesXML.ObjTree.VERSION = '0.23'//  object prototypeXML.ObjTree.prototype.xmlDecl = '<?xml version="1.0" encoding="UTF-8" ?>\n'
XML.ObjTree.prototype.attr_prefix = '-'//  method: parseXML( xmlsource )XML.ObjTree.prototype.parseXML = function(xml) {let rootif (window.DOMParser) {var xmldom = new DOMParser()//      xmldom.async = false;           // DOMParser is always sync-modeconst dom = xmldom.parseFromString(xml, 'application/xml')if (!dom) returnroot = dom.documentElement} else if (window.ActiveXObject) {xmldom = new ActiveXObject('Microsoft.XMLDOM')xmldom.async = falsexmldom.loadXML(xml)root = xmldom.documentElement}if (!root) returnreturn this.parseDOM(root)
}//  method: parseHTTP( url, options, callback )XML.ObjTree.prototype.parseHTTP = function(url, options, callback) {const myopt = {}for (const key in options) {myopt[key] = options[key] // copy object}if (!myopt.method) {if (typeof myopt.postBody === 'undefined' &&typeof myopt.postbody === 'undefined' &&typeof myopt.parameters === 'undefined') {myopt.method = 'get'} else {myopt.method = 'post'}}if (callback) {myopt.asynchronous = true // async-modeconst __this = thisconst __func = callbackconst __save = myopt.onCompletemyopt.onComplete = function(trans) {let treeif (trans && trans.responseXML && trans.responseXML.documentElement) {tree = __this.parseDOM(trans.responseXML.documentElement)}__func(tree, trans)if (__save) __save(trans)}} else {myopt.asynchronous = false // sync-mode}let transif (typeof HTTP !== 'undefined' && HTTP.Request) {myopt.uri = urlvar req = new HTTP.Request(myopt) // JSANif (req) trans = req.transport} else if (typeof Ajax !== 'undefined' && Ajax.Request) {var req = new Ajax.Request(url, myopt) // ptorotype.jsif (req) trans = req.transport}if (callback) return transif (trans && trans.responseXML && trans.responseXML.documentElement) {return this.parseDOM(trans.responseXML.documentElement)}
}//  method: parseDOM( documentroot )XML.ObjTree.prototype.parseDOM = function(root) {if (!root) returnthis.__force_array = {}if (this.force_array) {for (let i = 0; i < this.force_array.length; i++) {this.__force_array[this.force_array[i]] = 1}}let json = this.parseElement(root) // parse root nodeif (this.__force_array[root.nodeName]) {json = [json]}if (root.nodeType != 11) {// DOCUMENT_FRAGMENT_NODEconst tmp = {}tmp[root.nodeName] = json // root nodeNamejson = tmp}return json
}//  method: parseElement( element )XML.ObjTree.prototype.parseElement = function(elem) {//  COMMENT_NODEif (elem.nodeType == 7) {return}//  TEXT_NODE CDATA_SECTION_NODEif (elem.nodeType == 3 || elem.nodeType == 4) {const bool = elem.nodeValue.match(/[^\x00-\x20]/)if (bool == null) return // ignore white spacesreturn elem.nodeValue}let retvalconst cnt = {}//  parse attributesif (elem.attributes && elem.attributes.length) {retval = {}for (var i = 0; i < elem.attributes.length; i++) {var key = elem.attributes[i].nodeNameif (typeof key !== 'string') continuevar val = elem.attributes[i].nodeValueif (!val) continuekey = this.attr_prefix + keyif (typeof cnt[key] === 'undefined') cnt[key] = 0cnt[key]++this.addNode(retval, key, cnt[key], val)}}//  parse child nodes (recursive)if (elem.childNodes && elem.childNodes.length) {let textonly = trueif (retval) textonly = false // some attributes existsfor (var i = 0; i < elem.childNodes.length && textonly; i++) {const ntype = elem.childNodes[i].nodeTypeif (ntype == 3 || ntype == 4) continuetextonly = false}if (textonly) {if (!retval) retval = ''for (var i = 0; i < elem.childNodes.length; i++) {retval += elem.childNodes[i].nodeValue}} else {if (!retval) retval = {}for (var i = 0; i < elem.childNodes.length; i++) {var key = elem.childNodes[i].nodeNameif (typeof key !== 'string') continuevar val = this.parseElement(elem.childNodes[i])if (!val) continueif (typeof cnt[key] === 'undefined') cnt[key] = 0cnt[key]++this.addNode(retval, key, cnt[key], val)}}}return retval
}//  method: addNode( hash, key, count, value )XML.ObjTree.prototype.addNode = function(hash, key, cnts, val) {if (this.__force_array[key]) {if (cnts == 1) hash[key] = []hash[key][hash[key].length] = val // push} else if (cnts == 1) {// 1st siblinghash[key] = val} else if (cnts == 2) {// 2nd siblinghash[key] = [hash[key], val]} else {// 3rd sibling and morehash[key][hash[key].length] = val}
}//  method: writeXML( tree )XML.ObjTree.prototype.writeXML = function(tree) {const xml = this.hash_to_xml(null, tree)return this.xmlDecl + xml
}//  method: hash_to_xml( tagName, tree )XML.ObjTree.prototype.hash_to_xml = function(name, tree) {const elem = []const attr = []for (const key in tree) {if (!tree.hasOwnProperty(key)) continueconst val = tree[key]if (key.charAt(0) != this.attr_prefix) {if (typeof val === 'undefined' || val == null) {elem[elem.length] = `<${key} />`} else if (typeof val === 'object' && val.constructor == Array) {elem[elem.length] = this.array_to_xml(key, val)} else if (typeof val === 'object') {elem[elem.length] = this.hash_to_xml(key, val)} else {elem[elem.length] = this.scalar_to_xml(key, val)}} else {attr[attr.length] = ` ${key.substring(1)}="${this.xml_escape(val)}"`}}const jattr = attr.join('')let jelem = elem.join('')if (typeof name === 'undefined' || name == null) {// no tag} else if (elem.length > 0) {if (jelem.match(/\n/)) {jelem = `<${name}${jattr}>\n${jelem}</${name}>\n`} else {jelem = `<${name}${jattr}>${jelem}</${name}>\n`}} else {jelem = `<${name}${jattr} />\n`}return jelem
}//  method: array_to_xml( tagName, array )XML.ObjTree.prototype.array_to_xml = function(name, array) {const out = []for (let i = 0; i < array.length; i++) {const val = array[i]if (typeof val === 'undefined' || val == null) {out[out.length] = `<${name} />`} else if (typeof val === 'object' && val.constructor == Array) {out[out.length] = this.array_to_xml(name, val)} else if (typeof val === 'object') {out[out.length] = this.hash_to_xml(name, val)} else {out[out.length] = this.scalar_to_xml(name, val)}}return out.join('')
}//  method: scalar_to_xml( tagName, text )XML.ObjTree.prototype.scalar_to_xml = function(name, text) {if (name == '#text') {return this.xml_escape(text)}return `<${name}>${this.xml_escape(text)}</${name}>\n`
}//  method: xml_escape( text )XML.ObjTree.prototype.xml_escape = function(text) {return `${text}`.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
}export default XML

json 转为xml

const getIncoming = (id, data) => {return data.filter(item => item.targetRef === id).map(items => items.id)
}
const getOutGoing = (id, data) => {return data.filter(item => item.sourceRef === id).map(items => items.id)
}
const getLabel = (data, labelStyle) => {const keyWord = ['isBold', 'isItalic', 'isStrikeThrough', 'isUnderline', 'fontFamily', 'size']const arr = data.filter(item => {return keyWord.find(key => {return key in labelStyle})})return arr.map(item => {const obj = {}keyWord.forEach(key => {if (labelStyle[key]) {obj[key === 'fontFamily' ? 'name' : key] = labelStyle[key] || ''}})return {'-id': item.id,'omgdc:Font': obj}})
}
export function convertJsonToBpmn(jsonData) {if (!jsonData || !Object.keys(jsonData).length) return {}const result = {definitions: {'-xmlns': 'http://www.omg.org/spec/BPMN/20100524/MODEL','-xmlns:bpmndi': 'http://www.omg.org/spec/BPMN/20100524/DI','-xmlns:omgdi': 'http://www.omg.org/spec/DD/20100524/DI','-xmlns:omgdc': 'http://www.omg.org/spec/DD/20100524/DC','-xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance','-xmlns:bioc': 'http://bpmn.io/schema/bpmn/biocolor/1.0','-xmlns:color': 'http://www.omg.org/spec/BPMN/non-normative/color/1.0','-id': 'sid-38422fae-e03e-43a3-bef4-bd33b32041b2','-targetNamespace': 'http://bpmn.io/bpmn','-exporter': 'bpmn-js (https://demo.bpmn.io)','-exporterVersion': '5.1.2',process: {'-id': 'Process_1','-isExecutable': 'true',task: [],sequenceFlow: []},'bpmndi:BPMNDiagram': {'-id': 'BpmnDiagram_1','bpmndi:BPMNPlane': {'-id': 'BpmnPlane_1','-bpmnElement': 'Process_1','bpmndi:BPMNShape': [],'bpmndi:BPMNEdge': []}},'bpmndi:BPMNLabelStyle': {}}}// Convert tasksjsonData.nodeLists.forEach(task => {const taskId = task.config.idconst incoming = getIncoming(taskId, jsonData.lines)const outGoing = getOutGoing(taskId, jsonData.lines)const obj = {'-id': taskId}if (incoming.length > 1) {obj.incoming = incoming} else if (incoming.length === 1) {obj.incoming = incoming[0]}if (outGoing.length > 1) {obj.outgoing = outGoing} else if (outGoing.length === 1) {obj.outgoing = outGoing[0]}result.definitions.process.task.push(obj)const { x, y, width, height, labelStyle } = task.configconst element = {'-id': `${taskId}_di`,'-bpmnElement': taskId,'omgdc:Bounds': {'-x': x,'-y': y,'-width': width,'-height': height},'bpmndi:BPMNLabel': {}}if (labelStyle && Object.keys(labelStyle).length) {const { x, y, width, height, id } = labelStyleelement['bpmndi:BPMNLabel']['-labelStyle'] = idelement['bpmndi:BPMNLabel']['omgdc:Bounds'] = {'-x': x,'-y': y,'-width': width,'-height': height}result.definitions['bpmndi:BPMNLabelStyle'] = getLabel(jsonData.nodeLists, labelStyle)}// Convert BPMN shapesresult.definitions['bpmndi:BPMNDiagram']['bpmndi:BPMNPlane']['bpmndi:BPMNShape'].push(element)})// Convert sequence flowsjsonData.lines.forEach(line => {const sequenceFlowId = line.idconst sourceRef = line.sourceRefconst targetRef = line.targetRefresult.definitions.process.sequenceFlow.push({'-id': `${sequenceFlowId}`,'-name': line.name,'-sourceRef': sourceRef,'-targetRef': targetRef})// Convert BPMN edgesresult.definitions['bpmndi:BPMNDiagram']['bpmndi:BPMNPlane']['bpmndi:BPMNEdge'].push({'-id': `${sequenceFlowId}_di`,'-bpmnElement': sequenceFlowId,'omgdi:waypoint': line.point.map(p => {return { '-x': p.x, '-y': p.y }}),'bpmndi:BPMNLabel': {'omgdc:Bounds': {'-x': line.x,'-y': line.y,'-width': line.width,'-height': line.height}}})})return result
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/56412.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Apache StreamPark系列教程第一篇——安装和体验

一、StreamPark介绍 实时即未来,在实时处理流域 Apache Spark 和 Apache Flink 是一个伟大的进步,尤其是Apache Flink被普遍认为是下一代大数据流计算引擎, 我们在使用 Flink & Spark 时发现从编程模型, 启动配置到运维管理都有很多可以抽象共用的地方, 我们将一些好的经验…

Git企业开发控制理论和实操-从入门到深入(六)|多人协作开发

前言 那么这里博主先安利一些干货满满的专栏了&#xff01; 首先是博主的高质量博客的汇总&#xff0c;这个专栏里面的博客&#xff0c;都是博主最最用心写的一部分&#xff0c;干货满满&#xff0c;希望对大家有帮助。 高质量博客汇总 然后就是博主最近最花时间的一个专栏…

Prompt召唤 AI “生成”生产力,未来已来

如果说 2023 年的 AI 为世界带来了怎样的改变&#xff0c;那么大模型的狂飙发展&#xff0c; 无疑一马当先。以人机交互为例&#xff0c;“提示词工程师”&#xff08;又称“AI 召唤师”&#xff09;成为 21 世纪最脑洞大开的新兴职业&#xff0c;用自然语言写代码、召唤计算机…

《机器学习在车险定价中的应用》实验报告

目录 一、实验题目 机器学习在车险定价中的应用 二、实验设置 1. 操作系统&#xff1a; 2. IDE&#xff1a; 3. python&#xff1a; 4. 库&#xff1a; 三、实验内容 实验前的猜想&#xff1a; 四、实验结果 1. 数据预处理及数据划分 独热编码处理结果&#xff08;以…

本地部署 Stable Diffusion(Windows 系统)

相对于使用整合包&#xff0c;手动在 Windows 系统下本地部署 Stable Diffusion Web UI&#xff08;简称 SD-WebUI&#xff09;&#xff0c;更能让人了解一些事情的来龙去脉。 一、安装前置软件&#xff1a;Python 和 Git 1、安装 Python for windows。 下载地址 https://www.p…

数字化、智能化的酒店固定资产管理系统

酒店固定资产管理系统是一种专门为酒店行业定制的管理软件&#xff0c;可以帮助酒店管理者全面、准确地管理固定资产。该系统具有以下实际功能和特点&#xff1a;  资产库存功能&#xff1a;通过扫描二维码或手动输入条形码&#xff0c;完成酒店固定资产的有效总结&#xff0…

浅谈Java中的观察者模式

观察者模式是软件开发中常用的一种设计模式&#xff0c;它通过定义一对多的依赖关系&#xff0c;使得一个对象&#xff08;主题&#xff09;的状态变化可以通知多个其他对象&#xff08;观察者&#xff09;。 这种模式的优点是解耦和增加扩展性&#xff0c;用于实现对象之间的…

pdf.js构建时,报Cannot read property ‘createChildCompiler‘ of undefined #177的解决方法

在本地和CI工具进行构建时&#xff0c;报如下错误。 Cannot read property createChildCompiler of undefined #177解决方法&#xff1a; 找到vue.config.js&#xff0c;在 module.exports {parallel: false, //新增的一行chainWebpack(config) {....config.module.rule(&…

《自动驾驶与机器人中的SLAM技术》之GNSS相关基础知识总结

简介 本篇基于对《自动驾驶与机器人中的SLAM技术》中的GNSS定位相关基础知识进行总结用于备忘 知识点整理 GNSS(全球卫星导航系统)定位原理 GNSS 通过测量自身与地球周围各卫星的距离来确定自身的位置 , 而与卫星的距离主要是通过测量时间间隔来确定的 GNSS与GPS的关系 GPS(…

15. 查看开源项目

15.1 parser.add_argument ① 像运行Tensorboar一样&#xff0c;在Terminal终端&#xff0c;可以命令运行.py文件。 ② 如下图所示&#xff0c;Terminal终端运行.py文件时&#xff0c;--变量 后面的值是给变量进行赋值&#xff0c;赋值后再在.py文件中运行。例如 ./datasets/…

vue2 element 踩坑爬坑

动态增减表单项 这个其实官网有demo&#xff0c;但是自己也调试了好久&#xff0c;记录下&#xff0c;具体写法自己查看文档&#xff1a;https://element.eleme.cn/#/zh-CN/component/form 关键地方在于key&#xff0c;新增数组时&#xff0c;要在数据里增加个key&#xff0c;…

如何在 Kubernetes 中借助Ingress 实现灰度发布和蓝绿发布

前言 部署在 Kubernetes 集群中的应用&#xff0c;在升级发布时可能会存在的问题&#xff1a; 1&#xff0c;由于 Kuberneter 底层 Pod 容器生命周期与网络组件生命周期是异步管理的&#xff0c;在升级时如果没有处理好应用优雅退出的问题&#xff0c;就很容易导致 http 访问请…

Vscode自动移出不用的包

Vscode自动移出不用的包 在Vscode中删除不用的包、Vscode移出不用的包、Vscode移出不用的import包 设置 找到setting.json&#xff08;在字体设置里面&#xff09;&#xff0c;添加如下配置 "editor.codeActionsOnSave": { "source.organizeImports": tru…

FreeSWITCH 1.10.10 简单图形化界面1 - docker/脚本/ISO镜像安装

FreeSWITCH 1.10.10 简单图形化界面1 - docker/脚本/ISO镜像安装 0. 界面预览1. Docker安装1.1 下载docker镜像1.2 启动docker镜像1.3 登录 2. 脚本安装2.1 下载2.2 安装2.3 登录2.4 卸载程序 3. 镜像安装3.1 下载镜像3.2 安装镜像3.3 登录 0. 界面预览 http://myfs.f3322.net…

building and deploying a single-Master RocketMQ cluster

building and deploying a single-Master RocketMQ cluster 1 、下载RocketMQ安装包(这里是通过源码安装)2、安装3、启动nameserver4、启动borkerStart the broker serviceVerify that the broker service is started successfully, for example, the brokers ip is 192.168.1.…

android amazon 支付接入

流程&#xff1a; 申请 Amazon 开发者帐号 ---> 在 amazon 控制台添加应用 ---> 添加应用内商品&#xff08;消费类商品&#xff0c;授权类商品&#xff0c;订阅类商品&#xff09;---> 导出 JSON 文件 --->集成 Amazon 支付 ---> 将导出的 JSON 文件 copy 到 …

FairyGUI-Unity 异形屏适配

本文中会修改到FairyGUI源代码&#xff0c;涉及两个文件Stage和StageCamera&#xff0c;需要对Unity的屏幕类了解。 在网上查找有很多的异形屏适配操作&#xff0c;但对于FairyGUI相关的描述操作很少&#xff0c;这里我贴出一下自己在实际应用中的异形屏UI适配操作。 原理 获…

Python爬虫逆向实战案例(五)——YRX竞赛题第五题

题目&#xff1a;抓取全部5页直播间热度&#xff0c;计算前5名直播间热度的加和 地址&#xff1a;https://match.yuanrenxue.cn/match/5 cookie中m值分析 首先打开开发者工具进行抓包分析&#xff0c;从抓到的包来看&#xff0c;参数传递了查询参数m与f&#xff0c;同时页面中…

C++数据结构学习——双向循环链表

双向循环链表特点 **双向链接&#xff1a;**每个节点都包含两个指针&#xff0c;一个指向前一个节点&#xff08;前驱节点&#xff09;&#xff0c;另一个指向后一个节点&#xff08;后继节点&#xff09;。这种双向连接使得在链表中可以轻松地在两个方向上遍历节点。 **循环…

uniapp scrollview 滚动最新位置

uniapp 效果是模拟发送聊天信息&#xff0c;需要scrollview在收到新消息时滚动到底部最新的位置 项目是vue2的&#xff0c;代码如下 // 第一种 高度固定值 scrollToBottom(selector) {this.$nextTick(() > {const dom uni.createSelectorQuery().in(this).select(selecto…