DrawIo mxGraph: Using XmlToSvg loses shapes information - mxgraph

I am trying to convert XML to SVG using Java, but it looks like the shapes information is getting lost in the process.
Given a simple draw.io graph:
After running XmlToSvg.java I get:
I saved it as an uncompressed XML. I'm using the mxgraph-all.jar from the mxGraph Repo
Do you know if there are hidden settings to enable to preserve shapes and colors?

Short version
It looks like despite the claims on the GitHub page, no implementation except for JavaScript one is really fully featured and production ready. Particularly Java implementation (as well .Net and PHP server-side ones) doesn't support "Cube" shape out of the box.
More details
Colors
You didn't provide your example XML but when I generate similar graph I get something like
<?xml version="1.0" encoding="UTF-8"?>
<mxGraphModel dx="1426" dy="816" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850"
pageHeight="1100" background="#ffffff" math="0" shadow="0">
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<mxCell id="2" value="" style="ellipse;whiteSpace=wrap;html=1;" parent="1" vertex="1">
<mxGeometry x="445" y="60" width="230" height="150" as="geometry"/>
</mxCell>
<mxCell id="3" value="" style="ellipse;shape=doubleEllipse;whiteSpace=wrap;html=1;aspect=fixed;" parent="1" vertex="1">
<mxGeometry x="500" y="320" width="120" height="120" as="geometry"/>
</mxCell>
<mxCell id="4" value="" style="endArrow=classic;html=1;" parent="1" source="3" target="2" edge="1">
<mxGeometry width="50" height="50" relative="1" as="geometry">
<mxPoint x="430" y="510" as="sourcePoint"/>
<mxPoint x="480" y="460" as="targetPoint"/>
</mxGeometry>
</mxCell>
<mxCell id="5" value="" style="shape=cube;whiteSpace=wrap;html=1;" parent="1" vertex="1">
<mxGeometry x="80" y="320" width="170" height="110" as="geometry"/>
</mxCell>
</root>
</mxGraphModel>
Important thing here is that this XML does not contain any information about colors. Thus whole idea about "preserving colors" is wrong. In Java implementation you can configure "default colors" using an instance of mxStylesheet class and use it to init mxGraph object. For example to change colors to black and white you may do something like this:
mxStylesheet stylesheet = new mxStylesheet();
// configure "figures" aka "vertex"
{
Map<String, Object> style = stylesheet.getDefaultVertexStyle();
style.put(mxConstants.STYLE_FILLCOLOR, "#FFFFFF");
style.put(mxConstants.STYLE_STROKECOLOR, "#000000");
style.put(mxConstants.STYLE_FONTCOLOR, "#000000");
}
// configure "lines" aka "edges"
{
Map<String, Object> style = stylesheet.getDefaultEdgeStyle();
style.put(mxConstants.STYLE_STROKECOLOR, "#000000");
style.put(mxConstants.STYLE_FONTCOLOR, "#000000");
}
mxGraph graph = new mxGraph(stylesheet);
You may look at mxStylesheet.createDefaultVertexStyle and mxStylesheet.createDefaultEdgeStyle for some details.
Shapes
The "ellipse" shape is not handled correctly because there is no code to parse "ellipse;whiteSpace=wrap;html=1;" and understand that the shape should be "ellipse" (comapre this to the "double ellipse" style "ellipse;shape=doubleEllipse;whiteSpace=wrap;html=1;aspect=fixed;" that contains explicit shape value). In JS implementation the first part of the style seems to select a handler function that will handle the rest of the string and do actual work. There seems to be no such feature in Java implmenetation at all. You can work this around by using "named styles" feature and define default shape for corresponding "handler" in the same mxStylesheet object like this:
// I just copied the whole list of mxConstants.SHAPE_ here
// you probably should filter it by removing non-primitive shapes
// such as mxConstants.SHAPE_DOUBLE_ELLIPSE
String[] shapes = new String[] {
mxConstants.SHAPE_RECTANGLE,
mxConstants.SHAPE_ELLIPSE,
mxConstants.SHAPE_DOUBLE_RECTANGLE,
mxConstants.SHAPE_DOUBLE_ELLIPSE,
mxConstants.SHAPE_RHOMBUS,
mxConstants.SHAPE_LINE,
mxConstants.SHAPE_IMAGE,
mxConstants.SHAPE_ARROW,
mxConstants.SHAPE_CURVE,
mxConstants.SHAPE_LABEL,
mxConstants.SHAPE_CYLINDER,
mxConstants.SHAPE_SWIMLANE,
mxConstants.SHAPE_CONNECTOR,
mxConstants.SHAPE_ACTOR,
mxConstants.SHAPE_CLOUD,
mxConstants.SHAPE_TRIANGLE,
mxConstants.SHAPE_HEXAGON,
};
Map<String, Map<String, Object>> styles = stylesheet.getStyles();
for (String sh : shapes)
{
Map<String, Object> style = new HashMap<>();
style.put(mxConstants.STYLE_SHAPE, sh);
styles.put(sh, style);
}
Still you may notice that the list of the mxConstants.SHAPE_ doesn't contain "cube". In JS implementation "cube" is a compound shape that is handled by a specialized handler in examples/grapheditor/www/js/Shape.js which is not a part of the core library! It means that if you want to support such advanced shapes in your Java code, you'll have to roll out the code to handle it yourself.
P.S. With all those changes (hacks) the image I get using Java code from the XML in the first snippet is:

There is an XML-file, containing parameters of the most generic shapes. You should load it into stylesheet to make images look exactly as they were drawn in editor. Default stylesheet is default.xml.
So first of all make your code to get 2 things: stylesheet and diagram content.
String diagramText = getAsString(diagramPath);
String stylesheetText = getAsString(stylesheetPath);
Next, the simplest way to create SVG image is to utilize classes from mxgraph-core.jar. It looks like this
mxStylesheet stylesheet = new mxStylesheet(); // mxgraph-core.jar
InputSource is = new InputSource(new StringReader(stylesheetText));
Document document = documentBuilder.parse(is);
mxCodec codec = new mxCodec(document);
codec.decode(document.getDocumentElement(), stylesheet);
mxIGraphModel model = new mxGraphModel();
mxGraph graph = new mxGraph(model, context.stylesheet);
is = new InputSource(new StringReader(diagramText));
document = documentBuilder.parse(new InputSource(is));
codec = new mxCodec(document);
codec.decode(document.getDocumentElement(), model);
final Document svgDocument = documentBuilder.newDocument();
mxCellRenderer.drawCells(
graph,
null,
1d,
null,
new mxCellRenderer.CanvasFactory() {
#Override
public mxICanvas createCanvas(int width, int height) {
Element root = output.createElement("svg");
String w = Integer.toString(width);
String h = Integer.toString(height);
root.setAttribute("width", w);
root.setAttribute("height", h);
root.setAttribute("viewBox", "0 0 " + w + " " + h);
root.setAttribute("version", "1.1");
root.setAttribute("xmlns", "http://www.w3.org/2000/svg");
root.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
output.appendChild(root);
mxSvgCanvas canvas = new mxSvgCanvas(svgDocument);
canvas.setEmbedded(true);
return canvas;
}
});
return svgDocument; // this is the result
However, as SergGr pointed, Java implementation of mxgraph library doesn't contain some useful shapes. Their drawing rules are described by JavaScript functions in Shape.js.
I tried to execute that JavaScript in ScriptEngine shipped in Java standard library. Unfortunately this idea didn't work, because the JavaScript code somewhere deep inside interacts with browser.
But if we run the code in a browser, it works well. I did it successfully with HtmlUnit.
Write a JavaScript function to call from Java:
function convertToSVG(diagramText, stylesheetText) {
var stylesheet = new mxStylesheet();
var doc = mxUtils.parseXml(stylesheetText);
var stylesheetRoot = doc.documentElement;
var stylesheetCodec = new mxCodec(doc);
var dom = document.implementation;
stylesheetCodec.decode(stylesheetRoot, stylesheet);
doc = dom.createDocument(null, "div", null);
var model = new mxGraphModel();
var graph = new mxGraph(doc.documentElement, model, "exact", stylesheet);
doc = new DOMParser().parseFromString(diagram, "text/xml");
var codec = new mxCodec(doc);
codec.decode(doc.documentElement, model);
doc = dom.createDocument("http://www.w3.org/2000/svg", "svg", null);
var svgRoot = doc.documentElement;
var bounds = graph.getGraphBounds();
svgRoot.setAttribute("xmlns", "http://www.w3.org/2000/svg");
svgRoot.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
svgRoot.setAttribute("width", bounds.width);
svgRoot.setAttribute("height", bounds.height);
svgRoot.setAttribute("viewBox", "0 0 " + bounds.width + " " + bounds.height);
svgRoot.setAttribute("version", "1.1");
var svgCanvas = new mxSvgCanvas2D(svgRoot);
svgCanvas.translate(-bounds.x, -bounds.y);
var exporter = new mxImageExport();
var state = graph.getView().getState(model.root);
exporter.drawState(state, svgCanvas);
var result = new XMLSerializer().serializeToString(doc);
return result;
}
Load this text into String and run the following code
String jsFunction = getAsString("convertToSVG.js");
Path file = Files.createTempFile("44179673-", ".html"); // do not forget to delete it
String hmltText = "<html xmlns=\"http://www.w3.org/1999/xhtml\">"
+ "<head><title>Empty file</title></head><body/></html>";
Files.write(file, Arrays.asList(htmlText));
WebClient webClient = new WebClient(); // net.sourceforge.htmlunit:htmlunit
HtmlPage page = webClient.getPage(file.toUri().toString());
String initScript = ""
+ "var mxLoadResources = false;"
+ "var mxLoadStylesheets = false;"
+ "var urlParams = new Object();";
page.executeJavaScript(initScript);
page.executeJavaScript(getAsString("mxClient.min.js"));
page.executeJavaScript(getAsString("Graph.js")); // Shape.js depends on it
page.executeJavaScript(getAsString("Shapes.js"));
ScriptResult scriptResult = page.executeJavaScript(jsFunction);
Object convertFunc = scriptResult.getJavaScriptResult();
Object args[] = new Object[]{ diagramText, stylesheetText };
scriptResult = page.executeJavaScriptFunction(convertFunc, null, args, null);
String svg = scriptResult.getJavaScriptResult().toString();
The code above seems to work well for me.

Related

Labels for tooltips on primefaces barchartseries

I have tried to search both the forum and Google extensively, but I have problems understanding how I should make this work:
PrimeFaces6
I have a BarchartModel based on the tutorial in the ShowCase:
CODE: SELECT ALL
private BarChartModel initStatusBarChart() {
BarChartModel model = new BarChartModel();
ChartSeries statusMessages = new ChartSeries();
statusMessages.setLabel("Label"));
statusMessages.set("Some String 1", list1.size());
statusMessages.set("Some String 2", list2.size());
model.addSeries(statusMessages);
return model;
}
The issue is that on render, I get tooltips the format of
"1, 515" and "2, 432", where 515 and 432 are the sizes of list1 and list2, respectively.
How can I replace 1 and 2 with the values "Some String" 1 and 2 ? Have tried extending highlighter and using dataTipFormat, with no success.
I solved the problem using the datatip editor of the chart model (with Primefaces 6.1, by the way). I used this for a stacked bar chart.
I needed to apply this solution at two places: the backing bean and the JSF page.
In the backing bean I had to set a JavaScript function name this way:
barModel.setDatatipEditor("chartDatatipEditor");
I tried to set it using the corresponding tag attribute in the JSF page but to no effect.
In the JSF I inserted this JavaScript code:
<script type="text/javascript">
function chartDatatipEditor(str, seriesIndex, pointIndex, plot) {
//console.log('chartDatatipEditor: '+str+" - "+seriesIndex+" - "+pointIndex);
var point = seriesIndex+','+pointIndex;
#{bean.datatipsJs}
}
</script>
This JS function gets the chart coordinates as parameters. I concat them so that the following JS code gets easier.
seriesIndex is the index of the chart series. pointIndex is the index on the X scale of the diagram.
To find out what are the correct values for your chart you can uncomment the console.log line above.
The inserted JS code is constructed in the backing bean this way:
private Map<String, String> chartDatatips;
public String getDatatipsJs() {
StringBuilder sb = new StringBuilder("switch ( point ) {\n");
for (String point : chartDatatips.keySet()) {
sb.append("case '").append(point).append("': return '").append(chartDatatips.get(point)).append("'; break;\n");
}
sb.append("default: return 'Unknown point'; break; }");
return sb.toString();
}
The map chartDatatips has the coordinate point as key (e.g., "2,1") and the tooltip as value.
During the chart setup you obviously have to fill this map with useful details ;-)
Like this:
chartDatatips.put("2,5", "Label ...");
...
Hope this helps, if you didn't already solved this.
~Alex
Based on Alex's answer I have come up with this. Only requiring javascript - it displays the label and value:
In the backing bean, set a JavaScript function name this way:
barModel.setDatatipEditor("chartDatatipEditor");
In the HTML file:
function chartDatatipEditor(str, seriesIndex, pointIndex, plot) {
return plot.series[seriesIndex].label + ' - ' + plot.data[seriesIndex][pointIndex];
}

Add title to pdf using itext

{
Document document = new Document(PageSize.A3, 32, 32, 32, 32);
PdfWriter.getInstance(document, response.getOutputStream());
document.open();
HTMLWorker htmlWorker = new HTMLWorker(document);
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "", "");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("Select * from test3");
List arrlist = new ArrayList();
while(rs.next()){
String xa =rs.getString("display");
if(xa.equals("1")){
arrlist.add(rs.getString("question_text"));
}
}
Collections.shuffle(arrlist);
for(int i=0;i<5;i++){
String str = (String) arrlist.get(i);
htmlWorker.parse(new StringReader(str));
htmlWorker.parse(new StringReader("<br>"));
}
document.close();
}
Above is a code snippet which gets data from the database and displays on pdf.How do I add a title, logo,date and page no.to this?Please if anyone could help.I am using itext.
Please check out some of the page event examples. Currently, you're creating an unnamed PdfWriter instance. Change this into a named writer instance and declare a page event before opening the document instance:
PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
writer.setPageEvent(new MyPageEvents());
The MyPageEvents class is to be written by you. It needs to implement the PdfPageEvent interface, or, better yet, extend the PdfPageEventHelper class.
Adding a title, logo, date,... in the header is done by implementing the onEndPage() method. Do NOT use the onStartPage() method without reading the documentation!!!
Use these onEndPage() examples for inspiration.
To add an Image, add a member variable img to your page event, and add this to your constructor:
Image img = Image.getInstance(pathToImage);
img.setAbsolutePosition(36, 806);
Then in the onEndPage() method, do this:
writer.getDirectContent().addImage(img);
This will add the image at position x = 36, y = 806 (near the left top of the page). Note that it's important that you don't create a new Image instance for every new page, because that would result in a bloated PDF file. By creating the Image in the constructor of your page event and reusing the object, the image bytes will be present only once in the PDF file.

The image I add to a header doesn't appear

I'm trying to create a header with an image; the header is added, but the image is missing in header. My application is deployed on an Oracle Weblogic server (using Java EE and Hibernate).
I'm trying to create the image like this. getImage(seasonalFilter.getPictureFileId()).getAbsolutePath(). The image path is something like this: /tmp/6461346546165461313_65464.jpg.
Note that I want to add text under the image in the header (for every page).
public File convertHtmlToPdf(String JSONString, ExportQueryTypeDTO queryType, String htmlText, ExportTypeDTO type) throws VedStatException {
try {
File retFile = null;
FilterDTO filter = null;
HashMap<Object, Object> properties = new HashMap<Object, Object>(queryType.getHashMap());
filter = JSONCoder.decodeSeasonalFilterDTO(JSONString);
DateFormat formatter = new SimpleDateFormat("yyyy_MM_dd__HH_mm");
//logger.debug("<<<<<< HTML TEXT: " + htmlText + " >>>>>>>>>>>>>>>>");
StringBuilder tmpFileName = new StringBuilder();
tmpFileName.append(formatter.format(new Date()));
retFile = File.createTempFile(tmpFileName.toString(), type.getSuffix());
OutputStream out = new FileOutputStream(retFile);
com.lowagie.text.Document document = new com.lowagie.text.Document(com.lowagie.text.PageSize.LETTER);
com.lowagie.text.pdf.PdfWriter pdfWriter = com.lowagie.text.pdf.PdfWriter.getInstance(document, out);
document.open();
com.lowagie.text.html.simpleparser.HTMLWorker htmlWorker = new com.lowagie.text.html.simpleparser.HTMLWorker(document);
String str = htmlText.replaceAll("ű", "û").replaceAll("ő", "õ").replaceAll("Ő", "Õ").replaceAll("Ű", "Û");
htmlWorker.parse(new StringReader(str));
if (filter instanceof SeasonalFilterDTO) {
SeasonalFilterDTO seasonalFilter = (SeasonalFilterDTO) filter;
if (seasonalFilter.getPictureFileId() != null) {
logger.debug("Image absolutePath: " + getImage(seasonalFilter.getPictureFileId()).getAbsolutePath());
Image logo = Image.getInstance(getImage(seasonalFilter.getPictureFileId()).getAbsolutePath());
logo.setAlignment(Image.MIDDLE);
logo.setAbsolutePosition(0, 0);
logo.scalePercent(100);
Chunk chunk = new Chunk(logo, 0, 0);
HeaderFooter header = new HeaderFooter(new Phrase(chunk), true);
header.setBorder(Rectangle.NO_BORDER);
document.setHeader(header);
}
}
document.close();
return retFile;
} catch (Exception e) {
throw new VedStatException(e);
}
}
I really dislike your false allegation that "Every tutorial is based on C:\imagelocation\dsadsa.jpg"
I'm the author of two books and many tutorials about iText and I know for a fact that what you say doesn't make any sense. Take a look at my name: "Bruno Lowagie." You are using my name in your code, so please believe me when I say you're doing it completely wrong.
Instead of HTMLWorker, you should use XML Worker. HTMLWorker is no longer supported and will probably be removed from iText in the near future.
I see that you're also using the HeaderFooter class. This class has been removed several years ago. Please take a look at the newer examples: http://www.itextpdf.com/themes/keyword.php?id=221
These examples are written in Java; if you need the C# version, please look for the corresponding C# examples in the SVN repository.
Regarding images, you may want to read chapter 10 of my book.
Finally: please read http://lowagie.com/itext2

Accessing properties via a String in AS3

I have an engine I created a while back that loads objects into a container based on XML data. A really quick example of the XML would be like this:
<level>
<object cname="enemies.Robot">
<pos x="200" y="400" layer="mobiles" />
</object>
<object cname="Player">
<pos x="12" y="89" layer="mobiles" />
</object>
</level>
I have a class Environment that has a method loadLevel(data:XML) which I parse the XML through, then the function runs through the XML finding all object nodes and uses getDefinitionByName to determine which Object I want to create based on object.#cname.
From here, I have to manually define each property based on the XML like so;
obj.x = xml.pos.#x;
obj.y = xml.pos.#y;
etc.
I was wondering if there's an inbuilt method for setting a property based on a String. By this I mean something like so:
var mc:MovieClip = new MovieClip();
mc.someInbuiltFunctionThatSetsAProperty("alpha", 0.5);
This way I could change my XML to be more like so:
<object cname="Player">
<props>
<x>200</x>
<y>221</y>
<alpha>7834</alpha>
<health>Something</health>
<power>3</power>
</props>
</object>
And iterate through all the children of props to set all of my properties on the fly.
I know if I create an Object and set properties within it like so:
var obj:Object =
{
var1: "hello",
var2: "there",
name: "marty"
};
That you can then iterate through names/values using the for(String in Object) loop like this:
var i:String;
for(i in obj)
{
trace(i + ": " + obj[i]);
}
/**
* Output:
* var1: hello
* var2: there
* name: marty
*/
Is there maybe something even similar to that?
Surely there's a way, as here's an example of identifying a property using a String:
var ar:Array = [new MovieClip(), new MovieClip()];
ar.sortOn("alpha", Array.ASCENDING);
So just to make my question more to-the-point: I want to be able to get and set properties that I can identify using a String.
Why not using ["string property"] notation :
var mc:MovieClip=new MovieClip()
mc["alpha"] = 0.5 // setter
var alpha:Number=mc["alpha"] // getter
I'm not quite clear on what it is you're looking for exactly, but I have a general sense of what you're getting at and have a few suggestions for you. First, have a look at the documentation for the Object class in the AS3 Language Reference. Look specifically at the propertyIsEnumerable() and setPropertyIsEnumerable() methods. I think that's what you're asking about.
If not, you might want to look into the behavior of dynamic classes, which let you add variables to an object on the fly.

E4X Add CDATA content

Basically I need to define a node name and its CDATA content using variables.
var nodeName:String = "tag";
var nodeValue:String = "<non-escaped-content>";
Naively I thought this would work :
var xml:XML = <doc><{nodeName}><![CDATA[{nodeValue}]]></{nodeName}>
Outputs :
<doc><tag><![CDATA[{nodeValue}]]></tag></doc>
In a previous version of the script designed for FP9 I bypassed the problem by using :
new XMLNode( XMLNodeType.XMLNodeType.CDATA_NODE, nodeValue ); // ...
but this doesn't seem to work in FP10, and I have the feeling the method is somehow depreciated anyway.
Anyone an elegant solution for this ?
how about this:
var xml:XML = <doc><{nodeName}>{nodeValue}</{nodeName}></doc>
trace(xml.toXMLString());
outputs:
<doc>
<tag><non-escaped-content></tag>
</doc>
i admit, this is not CDATA, but i don't see a problem ... parsing requires a little more time, but OTOH, correct escaping much more robust than CDATA ...
the version with XMLNode uses the flash.xml package, which is for backwards compatibility with AS2 ... didn't even notice, it was gone under FP10 ... however, you could use this
var x:XML = new XML("<![CDATA[" + nodeValue + "]]>");
as a replacement and then use appendChild as you would with flash.xml ...
alternatively you could use it e4x style, if you wrap it in a function
function cdata(data:String):XML {
return = new XML("<![CDATA[" + data + "]]>");
}
and then
var xml:XML = <doc><{nodeName}>{cdata(nodeValue)}</{nodeName}></doc>
but personally, i think that strings, that are both text based and relatively short, should be escaped, rather then wrapped in CDATA ...
update:
i don't get your point here
"<" is very different than a "<"
that's what the whole thing is about ... :D ... "<" would be interpreted during parsing, whereas "<" is just reconverted to "<", so after parsing the XML, you will have exactly the same string as before ...
this is my code:
package {
import flash.display.MovieClip;
public class Main extends MovieClip {
public function Main():void {
var nodeName:String = "tag";
var nodeValue:String = "<non-escaped-content>";
var xml:XML = <doc><{nodeName}>{cdata(nodeValue)}</{nodeName}></doc>;
trace(cdata("test").toXMLString());
trace(xml.toXMLString());
}
private function cdata(data:String):XML {
return new XML("<![CDATA[" + data + "]]>");
}
}
}
works perfectly for me on flash player 10, compiled with flex sdk 4 ... don't have a flash IDE at hand, but when it comes to pure ActionScript results are almost definitely the same, so it should work (you can use that as your document class, if you want to, or simply instantiate it) ...
btw. the first trace shows, that the second example works, which is also quite obvious, since new XML(<String>) uses the native XML parser to create an XML from the given string ...
here is what the above generates:
<![CDATA[test]]>
<doc>
<tag><![CDATA[<non-escaped-content>]]></tag>
</doc>
works quite good for me ... :)
greetz
back2dos
The above cdata function needs to look like the following, notice the last ">" is escaped in code. Otherwise there's compile errors.
private function cdata(data:String):XML
{
return new XML("<![CDATA[" + data + "]]\>");
}
Thanks, cdata function is very useful. I wrote just new one.
function newNode(nodeName:String,nodeValue:String):XML{
return new XML(<{nodeName}>{cdata(nodeValue)}</{nodeName}>);
}
private function cdata(data:String, nodeName:String):XML{
return new XML( "<"+nodeName+"><![CDATA[" + data + "]]\></"+nodeName+">");
}
work fine :)
Here is another solution
public static function getCDATANode(data:String, tagName:String):void
{
var node:XML = new XML( "<" + tagName + "/>" );
var cdata:XML = new XML("<![CDATA[" + data + " ]]>");
node.appendChild(cdata);
trace("getCDATANode: ", node.toXMLString() );
}
Here's my solution without using functions:
var nodeName:String = "tag";
var nodeValue:String = "<non-escaped-content>";
var xml:XML = <doc><{nodeName}>{new XML("<![CDATA[" + nodeValue + "]]>")}</{nodeName}></doc>;
If you need to replace existing nodes content and keep node attributes you can use:
var newNodeValue:String = "<non-escaped-content>";
var xml:XML = <doc><tag attribute="true">This is node content</tag></doc>;
xml.tag[0].setChildren(new XMLList());
xml.tag[0].appendChild(new XML("<![CDATA[" + newNodeValue + "]]>"));