1

I need to create an xml from javascript where some xml element tag would contain simple string data while some will contain html data. for that i have created a function

function element(child, childValue) {
var element = document.createElementNS(url, child);
var elementText = document.createTextNode(childValue);
element.appendChild(elementText);
return element;
}

By calling abobe function this way "function(widgetData, widget1)". it creates below xml element.

"<widgetData>widget1<widgetData>"

Now i need to create xml tag containing html data for that calling above function following way

function(widgetData, '<p>hello, world </p>')

it creates below xml element

<widgetData>&lt;p&gt;Hello, world&lt;/p&gt;</widgetData>

I think we can do this by CDATA

<widgetData><![CDATA[<p>hello, world </p>]]></widgetData>

But don't know how to do it.

I tried

var elementText = document.CreateCDataSection(childValue);

but it is giving error "undefined function" in chrome .And in Firefox "Unsupported html document" error occurs.

1 Answer 1

2

You'll want to use .createCDATASection

The following should work:

function element(child, childValue) {
  var element = document.createElementNS(url, child);
  var section = document.createCDATASection(childValue);
  element.appendChild(section);
  return element;
}

Please note:

This will only work with XML, not HTML documents (as HTML documents do not support CDATA sections); attempting it on an HTML document will throw NOT_SUPPORTED_ERR.

Sign up to request clarification or add additional context in comments.

4 Comments

executing above code getting error "Failed to execute 'createCDATASection' on 'Document': This operation is not supported for HTML documents."
in firefox getting exception "[Exception... "Operation is not supported" code: "9" nsresult: "0x80530009 (NotSupportedError)" location: "<unknown>"]"
I quoted an important bit from the docs, which likely explains this error. In short, you'll have to use it with real XML documents.
Thanks for your help and effort.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.