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 ?

4
  • Have you tried this: stackoverflow.com/a/27574931/573218 Commented Nov 3, 2015 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. Commented Nov 3, 2015 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) Commented Nov 3, 2015 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. Commented Nov 3, 2015 at 14:49

2 Answers 2

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/

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

Comments

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>");

Comments

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.