0

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 ?

Mike
  • 1,122
  • 2
  • 13
  • 25
  • Have you tried this: http://stackoverflow.com/a/27574931/573218 – John Koerner Nov 03 '15 at 14:27
  • the proper way is write C# and JS separately, and invoke C# from JS (e.g. Web API) to get needed info. – Alex Sikilinda Nov 03 '15 at 14:30
  • @JohnKoerner the post describes how to get the string encoded using a web framework, i dont have those utils at my disposal, only c# (no @{cats} notation) – Mike Nov 03 '15 at 14:34
  • @AlexSikilinda i guess proper is based on the usage, in my case i need the file to be present before sending to be interpreted in the js engine. – Mike Nov 03 '15 at 14:49

2 Answers2

1

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

string xmlInJavascript = JsonConvert.SerializeObject("<root><item1>123</item1></root>");
Artyom
  • 3,507
  • 2
  • 34
  • 67
1

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/

Frank Rem
  • 3,632
  • 2
  • 25
  • 37