[英]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 我正在尝试使用c#编写一个函数,该函数接收XML文件,并输出一个JavaScript文件,该文件的XML内容已分配给字符串变量
example 例
XML input: a.xml XML输入:a.xml
<root>
<book id="a">
SAM
</book>
<book id="b">
</book>
MAX
</root>
JS Output: b.js JS输出: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. 我正在寻找一种创建合法输出的简单方法,因为尝试手动转义所有xml字符以创建合法js字符串肯定会失败。
any ideas how this can be done painlessly ? 有什么想法可以毫不费力地做到这一点吗?
Read all text from your XML file using the following method in the System.IO namespace: 使用System.IO命名空间中的以下方法从XML文件中读取所有文本:
public static string ReadAllText(
string path
)
Pass this to the following method in the System.Web namespace (requires .NET 4.6): 将其传递给System.Web命名空间中的以下方法(需要.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: 给定您提供的XML示例,生成的JS如下所示:
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/ 这是小提琴: https : //jsfiddle.net/o1juvc0f/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.