How to get the XML from mxGrpah diagram?

2020-02-13 06:56发布

问题:

  • Pointed index.html from mxGraph diagram sample
  • Able to draw the diagrams using editor
  • Enabled local storage
  • Able to get the XML from local storage

Editor.useLocalStorage = true;
var temp = localStorage['testing.xml'];
console.log(temp);

But, I want to get the XML dynamically without using local storage, So I used the code from mxGraph -Save functionality not working locally but it's throwing graph is not defined

let encoder = new mxCodec();
let result = encoder.encode(graph.getModel());
let xml = mxUtils.getXml(result);

Code:

<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=5,IE=9" ><![endif]-->
<!DOCTYPE html>
<html>
<head>
    <title>Grapheditor</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link rel="stylesheet" type="text/css" href="styles/grapheditor.css">
	<script type="text/javascript">
		// Parses URL parameters. Supported parameters are:
		// - lang=xy: Specifies the language of the user interface.
		// - touch=1: Enables a touch-style user interface.
		// - storage=local: Enables HTML5 local storage.
		// - chrome=0: Chromeless mode.
		var urlParams = (function(url)
		{
			var result = new Object();
			var idx = url.lastIndexOf('?');
	
			if (idx > 0)
			{
				var params = url.substring(idx + 1).split('&');
				
				for (var i = 0; i < params.length; i++)
				{
					idx = params[i].indexOf('=');
					
					if (idx > 0)
					{
						result[params[i].substring(0, idx)] = params[i].substring(idx + 1);
					}
				}
			}
			
			return result;
		})(window.location.href);
	
		// Default resources are included in grapheditor resources
		mxLoadResources = false;
	</script>
	<script type="text/javascript" src="js/Init.js"></script>
	<script type="text/javascript" src="deflate/pako.min.js"></script>
	<script type="text/javascript" src="deflate/base64.js"></script>
	<script type="text/javascript" src="jscolor/jscolor.js"></script>
	<script type="text/javascript" src="sanitizer/sanitizer.min.js"></script>
	<script type="text/javascript" src="../../../src/js/mxClient.js"></script>
	<script type="text/javascript" src="js/EditorUi.js"></script>
	<script type="text/javascript" src="js/Editor.js"></script>
	<script type="text/javascript" src="js/Sidebar.js"></script>
	<script type="text/javascript" src="js/Graph.js"></script>
	<script type="text/javascript" src="js/Format.js"></script>
	<script type="text/javascript" src="js/Shapes.js"></script>
	<script type="text/javascript" src="js/Actions.js"></script>
	<script type="text/javascript" src="js/Menus.js"></script>
	<script type="text/javascript" src="js/Toolbar.js"></script>
	<script type="text/javascript" src="js/Dialogs.js"></script>
</head>
<body class="">


	<div class="actions" style="margin-bottom:25px">
		<input type="button" value="Save" onclick="getxml()" />
	</div>
    </br></br></br></br></br>
<div class="geEditor">
	<script type="text/javascript">

	function getxml(){
		console.log("Show XML");
		var temp = localStorage['testing.xml']; 
        console.log(temp);     
        
      /*   var graph = new Graph();
        var encoder = new mxCodec();
        //var result = encoder.encode(this.graph.getModel());
        //var xmlString = encodeURIComponent(mxUtils.getXml(result));        
        var xml = mxUtils.getXml(Editor.prototype.getGraphXml());
        console.log("Direct XML");
        console.log(xmlString); */
        //console.log(xml);

      /*   var graph = new Graph();
        //var encoder = new mxCodec(); 
        var node = encoder.encode(graph.getModel()); 
        var graphXML =mxUtils.getPrettyXml(node); */
        //var graphXMLWhole = mxUtils.getPrettyXml(Editor.prototype.getGraphXml());
        
        

        //mxUtils.popup(mxUtils.getPrettyXml(node), true)

        //var graph = this.editorUi.editor.graph;
      /*   var editorui = EditorUi;
        var xmlString = mxUtils.getXml(editorUi.editor.getGraphXml());
         */
           //console.log(xmlString);
           /* var encoder = new mxCodec();
            var node = encoder.encode(graph.getModel());

            var testString = mxUtils.getXml(node);
            console.log(testString);
 */

         /*    var encoder = new mxCodec();
            //let graph = new Graph();
            var editor = this.editor || new Editor();
            var graph = this.editor.graph || new Graph(); */
           /* // var model = graph.getxml();
            var result = encoder.encode(graph.getModel()); //where graph is the object you are using
            var xml = mxUtils.getXml(result);
            console.log(xml);
             //var xml = mxUtils.getXml(result); //now the global variable 'xml' is assigned with the xml value of the graph
             */
            var encoder  = new mxCodec(); 
            var node = encoder.encode(graph.getmodel()); 
            var xml = mxutils.getxml(node);  //mxutils.popup(xml, true); return xml; 

            // var xml = mxUtils.getXml(this.editor.getGraphXml())
             console.log(xml);

        	}
		// Extends EditorUi to update I/O action states based on availability of backend
		(function()
		{
			var editorUiInit = EditorUi.prototype.init;

			Editor.useLocalStorage = true;
            			
			EditorUi.prototype.init = function()
			{
				editorUiInit.apply(this, arguments);
				this.actions.get('export').setEnabled(false);

				// Updates action states which require a backend
				if (!Editor.useLocalStorage)
				{
					mxUtils.post(OPEN_URL, '', mxUtils.bind(this, function(req)
					{
						var enabled = req.getStatus() != 404;
						this.actions.get('open').setEnabled(enabled || Graph.fileSupport);
						this.actions.get('import').setEnabled(enabled || Graph.fileSupport);
						this.actions.get('save').setEnabled(true)
						this.actions.get('saveAs').setEnabled(true);
						this.actions.get('export').setEnabled(enabled);
					}));
				}
			};

			console.log("on init");
						
			// Adds required resources (disables loading of fallback properties, this can only
			// be used if we know that all keys are defined in the language specific file)
			mxResources.loadDefaultBundle = false;
			var bundle = mxResources.getDefaultBundle(RESOURCE_BASE, mxLanguage) ||
				mxResources.getSpecialBundle(RESOURCE_BASE, mxLanguage);

			// Fixes possible asynchronous requests
			mxUtils.getAll([bundle, STYLE_PATH + '/default.xml'], function(xhr)
			{
				// Adds bundle text to resources
				mxResources.parse(xhr[0].getText());
				
				// Configures the default graph theme
				var themes = new Object();
				themes[Graph.prototype.defaultThemeName] = xhr[1].getDocumentElement(); 
				
				// Main
				new EditorUi(new Editor(urlParams['chrome'] == '0', themes));
			}, function()
			{
				document.body.innerHTML = '<center style="margin-top:10%;">Error loading resource files. Please check browser console.</center>';
			});
		})();
	</script>
  </div>
</body>
</html>

回答1:

Well in the www/index.html where it seems your example to be taken from it is not very clear to me where the Graph exists so you can retrieve it but I propose you the following workaround to solve your problem:

1) Add an extra variable holding the "xml" state of the graph which you can retrieve any time

In the /examples/grapheditor/www/js/Graph.js add the following variable

Graph.xml = "";

2) On the this.graph.click event of Graph.js add code to retrieve to update the Graph.xml variable holding the xml state of the graph each time there is a change so instead of

this.graph.click = mxUtils.bind(this, function(me)
{
    graphClick.apply(this.graph, arguments);

    if (this.currentState != null && !this.graph.isCellSelected(this.currentState.cell) &&
        mxEvent.isTouchEvent(me.getEvent()) && !this.graph.model.isVertex(me.getCell()))
    {
        this.reset();
    }
});

add the following:

this.graph.click = mxUtils.bind(this, function(me)
{
    let encoder = new mxCodec();
    let result = encoder.encode(this.graph.getModel()); //where graph is the object you are using
    Graph.xml  = mxUtils.getXml(result);

    graphClick.apply(this.graph, arguments);

    if (this.currentState != null && !this.graph.isCellSelected(this.currentState.cell) &&
        mxEvent.isTouchEvent(me.getEvent()) && !this.graph.model.isVertex(me.getCell()))
    {
        this.reset();
    }
});

So when you want the xml state of the canvas you should call the Graph.xml, this worked for me in a local environment



回答2:

Did you try this?

  var enc = new mxCodec(mxUtils.createXmlDocument());
  var node = enc.encode(graph.getModel());
  var xmlString = mxUtils.getXml(node);


回答3:

<?php
                // Includes the mxGraph library
                include_once("_js/mxgraph/php/src/mxServer.php");

                $xml =  $_POST['xml'];
                $xml = output_html($xml);
                $xml = str_replace("%3C", "<", $xml);
                $xml = str_replace("%3E", ">", $xml);
                $xml = str_replace("%22", '"', $xml);
                $xml = str_replace("%20", " ", $xml);
                $xml = str_replace("%3D", "=", $xml);
                $xml = str_replace("%2F", "/", $xml);
                $xml = str_replace("%3B", ";", $xml);
                $xml = str_replace("%23", "#", $xml);

                // XML
                $fh = fopen("xml.xml", "w+");
                fputs($fh, stripslashes($xml)); 
                fclose($fh);

?>

output_html:

<?php
/**
*
* File: _admin/_functions/output_html.php
* Version 2 - Updated 19:31 06.03.2015
* Copyright (c) 2008-2015 S. Ditlefsen
* License: http://opensource.org/licenses/gpl-license.php GNU Public License
*
*
*
* -----> Please also see: encode_national_letters.php <-----
* encode_national_letters.php are used when this class cannot be used, because
* this class also removes html entities. Example SQL with links, bold text etc
*
*
*/
function output_html($value){
    // Stripslashes
    $value = htmlentities($value);
    $value = str_replace('"',"&quot;","$value");
    $value = str_replace("'","&#039;","$value");
    $value = str_replace("<","&gt;","$value"); // less than
    $value = str_replace(">","&lt;","$value"); // greater than
    $value = str_replace("\n","<br />","$value");

    // Trim and line space
    $value = trim($value);

    // Math
    $value = str_replace("&amp;#699;","&#39;","$value");
    $value = str_replace("&amp;#3647;","&#3647;","$value");
    $value = str_replace("&amp;#960;","&#960;","$value"); // pi
    $value = str_replace("&amp;#966;","&#966;","$value"); // phi
    $value = str_replace('÷', '&#247;', $value);  // Yeah, I know.  But otherwise the gap is confusing.  --Kris

    // Check last, if it is backslash, then replace it...
    $check  = substr($value, -1);
    $check  =  "^" . $check . "^";
    if($check == "^\^"){
        $new_value = substr($value, 0, -1);
        $value   = $new_value . "&#92";
    }

    // A
    $value = str_replace('æ', '&aelig;', $value);
    $value = str_replace("æ", "&aelig;", $value);
    $value = str_replace("&amp;aelig;", "&aelig;", $value);
    $value = str_replace('ø', '&oslash;', $value);
    $value = str_replace('ø', '&oslash;', $value);
    $value = str_replace('&amp;oslash;', '&oslash;', $value);
    $value = str_replace("å", "&aring;", $value);
    $value = str_replace("Ã¥", "&aring;", $value);
    $value = str_replace("&amp;aring;", "&aring;", $value);
    $value = str_replace('Æ', '&AElig;', $value);
    $value = str_replace('Æ', '&AElig;', $value);
    $value = str_replace('&amp;AElig;', '&AElig;', $value);
    $value = str_replace('Å', '&Aring;', $value);
    $value = str_replace('Ã…', '&Aring;', $value);
    $value = str_replace('&amp;Aring;', '&Aring;', $value);

    $value = str_replace('á', '&aacute;', $value);
    $value = str_replace('à', '&agrave;', $value);
    $value = str_replace('À', '&Agrave;', $value);
    $value = str_replace('â', '&acirc;', $value);
    $value = str_replace('Â', '&Acirc;', $value);
    $value = str_replace('Á', '&Aacute;', $value);


    $value = str_replace('Ä', '&Auml;', $value);
    $value = str_replace('ä', '&auml;', $value);


    $value = str_replace('À', '&#192;', $value);
    $value = str_replace('Á', '&#193;', $value);
    // $value = str_replace('Â', '&#194;', $value);
    // $value = str_replace('Ã', '&#195;', $value);
    $value = str_replace('Ä', '&#196;', $value);
    $value = str_replace('à', '&#224;', $value);
    $value = str_replace('á', '&#225;', $value);
    $value = str_replace('â', '&#226;', $value);
    $value = str_replace('ã', '&#227;', $value);
    $value = str_replace('ä', '&#228;', $value);

    // C
    $value = str_replace('Ç', '&#199;', $value);
    $value = str_replace('ç', '&#231;', $value);


    // E
    $value = str_replace('è', '&egrave;', $value);
    $value = str_replace('È', '&Egrave;', $value);
    $value = str_replace('é', '&eacute;', $value);
    $value = str_replace('É', '&Eacute;', $value);
    $value = str_replace('ê', '&ecirc;', $value);
    $value = str_replace('Ê', '&Ecirc;', $value);
    $value = str_replace('ë', '&euml;', $value);
    $value = str_replace('Ë', '&Euml;', $value);
    $value = str_replace('È', '&#200;', $value);
    $value = str_replace('É', '&#201;', $value);
    $value = str_replace('Ê', '&#202;', $value);
    $value = str_replace('Ë', '&#203;', $value);
    $value = str_replace('è', '&#232;', $value);
    $value = str_replace('é', '&#233;', $value);
    $value = str_replace('ê', '&#234;', $value);
    $value = str_replace('ë', '&#235;', $value);

    // I
    $value = str_replace('î', '&icirc;', $value);
    $value = str_replace('Î', '&Icirc;', $value);
    $value = str_replace('ï', '&iuml;', $value);
    $value = str_replace('Ï', '&Iuml;', $value);
    $value = str_replace('Í', '&Iacute;', $value);
    $value = str_replace('í', '&iacute;', $value);
    $value = str_replace('¿', '&iquest;', $value);
    $value = str_replace('¡', '&iexcl;', $value);
    $value = str_replace('Ì', '&#204;', $value);
    $value = str_replace('Í', '&#205;', $value);
    $value = str_replace('Î', '&#206;', $value);
    $value = str_replace('Ï', '&#207;', $value);
    $value = str_replace('ì', '&#236;', $value);
    $value = str_replace('í', '&#237;', $value);
    $value = str_replace('î', '&#238;', $value);
    $value = str_replace('ï', '&#239;', $value);

    // D
    $value = str_replace('Ð', '&#208;', $value);

    // N
    $value = str_replace('Ñ', '&Ntilde;', $value);
    $value = str_replace('ñ', '&ntilde;', $value);
    $value = str_replace('Ñ', '&#209;', $value);

    // O
    $value = str_replace('Ø', '&Oslash;', $value);
    $value = str_replace('Ø', '&Oslash;', $value);
    $value = str_replace('&amp;Oslash;', '&Oslash;', $value);
    $value = str_replace('ô', '&ocirc;', $value);
    $value = str_replace('Ô', '&Ocirc;', $value);
    $value = str_replace('Ó', '&Oacute;', $value);
    $value = str_replace('ó', '&oacute;', $value);
    $value = str_replace('º', '&ordm;', $value);
    $value = str_replace('ª', '&ordf;', $value);
    $value = str_replace('Ö', '&Ouml;', $value);
    $value = str_replace('ö', '&ouml;', $value);
    $value = str_replace('Ò', '&#210;', $value);
    $value = str_replace('Ó', '&#211;', $value);
    $value = str_replace('Ô', '&#212;', $value);
    $value = str_replace('Õ', '&#213;', $value);
    $value = str_replace('Ö', '&#214;', $value);
    $value = str_replace('ð', '&#240;', $value);
    $value = str_replace('ñ', '&#241;', $value);
    $value = str_replace('ò', '&#242;', $value);
    $value = str_replace('ó', '&#243;', $value);
    $value = str_replace('ô', '&#244;', $value);
    $value = str_replace('õ', '&#245;', $value);
    $value = str_replace('ö', '&#246;', $value);

    // P
    $value = str_replace('Þ', '&#222;', $value);
    $value = str_replace('þ', '&#254;', $value);

    // S
    $value = str_replace('ß', '&#223;', $value);

    // U
    $value = str_replace('ù', '&ugrave;', $value);
    $value = str_replace('Ù', '&Ugrave;', $value);
    $value = str_replace('û', '&ucirc;', $value);
    $value = str_replace('Û', '&Ucirc;', $value);
    $value = str_replace('ü', '&uuml;', $value);
    $value = str_replace('Ü', '&Uuml;', $value);
    $value = str_replace('Ú', '&Uacute;', $value);
    $value = str_replace('ú', '&uacute;', $value);
    $value = str_replace('ü', '&uuml;', $value);
    $value = str_replace('Ù', '&#217;', $value);
    $value = str_replace('Ú', '&#218;', $value);
    $value = str_replace('Û', '&#219;', $value);
    $value = str_replace('Ü', '&#220;', $value);
    $value = str_replace('ù', '&#249;', $value);
    $value = str_replace('ú', '&#250;', $value);
    $value = str_replace('û', '&#251;', $value);
    $value = str_replace('ü', '&#252;', $value);

    // Y
    $value = str_replace('ÿ', '&yuml;', $value);
    $value = str_replace('Ÿ', '&Yuml;', $value);
    $value = str_replace('Ý', '&#221;', $value);
    $value = str_replace('ý', '&#253;', $value);
    $value = str_replace('ÿ', '&#255;', $value);

    // X
    $value = str_replace('×', '&#215;', $value);  // Yeah, I know.  But otherwise the gap is confusing.  --Kris


    // Other
    $value = str_replace('ç', '&ccedil;', $value);
    $value = str_replace('Ç', '&Ccedil;', $value);
    $value = str_replace('œ', '&oelig;', $value);
    $value = str_replace('Œ', '&OElig;', $value);

    //Punctuation
    $value = str_replace('«', '&laquo;', $value);
    $value = str_replace('»', '&raquo;', $value);
    $value = str_replace('‹', '&lsaquo;', $value);
    $value = str_replace('›', '&rsaquo;', $value);
    $value = str_replace('“', '&ldquo;', $value);
    $value = str_replace('”', '&rdquo;', $value);
    $value = str_replace('‘', '&lsquo;', $value);
    $value = str_replace('’', '&rsquo;', $value);
    $value = str_replace('—', '&mdash;', $value);
    $value = str_replace('–', '&ndash;', $value);

    // Money
    $value = str_replace('€', '&euro;', $value);

    // Degree
    $value = str_replace('°', '&deg;', $value);
    $value = str_replace('&amp;deg;', '&deg;', $value);

    // &
    $value = str_replace('&amp;amp;', '&amp;', $value);


    // Return
    return $value;
}
?>