简体   繁体   中英

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 ?

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

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM