Mike
Mike

Reputation: 1172

create a legal javascript file using c#

Using c# I am trying to write a function that receives an XML file, and outputs a JavaScript file with XML content assigned to a string variable

example

XML input: a.xml

<root>
 <book id="a">
   SAM 
 </book>
 <book id="b">
 </book>
   MAX
</root>

JS Output: b.js

var xml =   "<root><book id='a'>SAM</book><book id='b'></book>MAX</root>";

Im looking for a simple way to create a legal output as trying to manually escape all xml chars to create a legal js string will surely fail.

any ideas how this can be done painlessly ?

Upvotes: 0

Views: 1098

Answers (2)

Frank Rem
Frank Rem

Reputation: 3738

Read all text from your XML file using the following method in the System.IO namespace:

public static string ReadAllText(
    string path
)

Pass this to the following method in the System.Web namespace (requires .NET 4.6):

public static string JavaScriptStringEncode(
    string value,
    bool addDoubleQuotes
)

The combined code would look like this:

string xml = File.ReadAllText(@"..\..\a.xml");
string js = HttpUtility.JavaScriptStringEncode(xml, false);
File.WriteAllText(@"..\..\b.js", string.Format("var xml=\"{0}\";", js));

Given the XML example you provided, the resulting JS looks like this:

var xml="\u003croot\u003e\r\n    \u003cbook id=\"a\"\u003e\r\n        SAM\r\n    \u003c/book\u003e\r\n    \u003cbook id=\"b\"\u003e\r\n    \u003c/book\u003e\r\n    MAX\r\n\u003c/root\u003e";

And here is the fiddle: https://jsfiddle.net/o1juvc0f/

Upvotes: 1

Artyom
Artyom

Reputation: 3571

You can try Json.Net. It is serializer for JSON (subset of Javascript). Just try:

string xmlInJavascript = JsonConvert.SerializeObject("<root><item1>123</item1></root>");

Upvotes: 1

Related Questions