corrade-nucleus-nucleons – Blame information for rev

Subversion Repositories:
Rev:
Rev Author Line No. Line
1 office 1 x2js - XML to JSON and vice versa for JavaScript
2 ====
3 This library provides XML to JSON (JavaScript Objects) and vice versa javascript conversion functions.
4 The library is very small and has no any dependencies.
5  
6 ## API functions
7  
8 * `new X2JS()` - to create your own instance to access all library functionality
9 * `new X2JS(config)` - to create your own instance with additional config
10  
11 * `<instance>.xml2json` - Convert XML specified as DOM Object to JSON
12 * `<instance>.json2xml` - Convert JSON to XML DOM Object
13 * `<instance>.xml_str2json` - Convert XML specified as string to JSON
14 * `<instance>.json2xml_str` - Convert JSON to XML string
15 * `<instance>.asArray` - Utility function to work with a JSON field always in array form
16 * `<instance>.asDateTime` - Utility function to convert the specified parameter from XML DateTime to JS Date
17 * `<instance>.asXmlDateTime` - Utility function to convert the specified parameter to XML DateTime from JS Date or timestamp
18  
19 ## Config options
20  
21 * `escapeMode : true|false` - Escaping XML characters. Default is true from v1.1.0+
22 * `attributePrefix : "<string>"` - Prefix for XML attributes in JSon model. Default is "_"
23 * `arrayAccessForm : "none"|"property"` - The array access form (none|property). Use this property if you want X2JS generates additional property <element>_asArray to access in array form for any XML element. Default is none from v1.1.0+
24 * `emptyNodeForm : "text"|"object"` - Handling empty nodes (text|object) mode. When X2JS found empty node like <test></test> it will be transformed to test : '' for 'text' mode, or to Object for 'object' mode. Default is 'text'
25 * `enableToStringFunc : true|false` - Enable/disable an auxiliary function in generated JSON objects to print text nodes with text/cdata. Default is true
26 * `arrayAccessFormPaths : []` - Array access paths - use this option to configure paths to XML elements always in "array form". You can configure beforehand paths to all your array elements based on XSD or your knowledge. Every path could be a simple string (like 'parent.child1.child2'), a regex (like /.*\.child2/), or a custom function. Default is empty
27 * `skipEmptyTextNodesForObj : true|false` - Skip empty text tags for nodes with children. Default is true.
28 * `stripWhitespaces : true|false` - Strip whitespaces (trimming text nodes). Default is true.
29 * `datetimeAccessFormPaths : []` - DateTime access paths. Use this option to configure paths to XML elements for XML datetime elements. You can configure beforehand paths to all your datetime elements based on XSD or your knowledge. Every path could be a simple string (like 'parent.child1.child2'), a regex (like /.*\.child2/), or a custom function. Default is empty.
30 * `useDoubleQuotes : true|false` - Use double quotes for output XML formatting. Default is false.
31 * `xmlElementsFilter : []` - Filter incoming XML elements. You can pass a stringified path (like 'parent.child1.child2'), regexp or function
32 * `jsonPropertiesFilter : []` - Filter JSON properties for output XML. You can pass a stringified path (like 'parent.child1.child2'), regexp or function
33 * `keepCData : true|false` - If this property defined as false and an XML element has only CData node it will be converted to text without additional property "__cdata". Default is false.
34  
35 ## Online demo
36  
37 JSFiddle at http://jsfiddle.net/abdmob/gkxucxrj/1/
38  
39  
40 # Basic Usage
41  
42 ## XML to JSON
43  
44 ```
45 // Create x2js instance with default config
46 var x2js = new X2JS();
47 var xmlText = "<MyRoot><test>Success</test><test2><item>val1</item><item>val2</item></test2></MyRoot>";
48 var jsonObj = x2js.xml_str2json( xmlText );
49 ```
50  
51 ## JSON to XML
52  
53 ```
54 // Create x2js instance with default config
55 var x2js = new X2JS();
56 var jsonObj = {
57 MyRoot : {
58 test: 'success',
59 test2 : {
60 item : [ 'val1', 'val2' ]
61 }
62 }
63 };
64 var xmlAsStr = x2js.json2xml_str( jsonObj );
65 ```
66  
67 # Working with arrays
68  
69 ## Configure XML structure knowledge beforehand
70  
71 ```
72 var x2js = new X2JS({
73 arrayAccessFormPaths : [
74 "MyArrays.test.item"
75 ]
76 });
77  
78  
79 var xmlText = "<MyArrays>"+
80 "<test><item>success</item><item>second</item></test>"+
81 "</MyArrays>";
82  
83 var jsonObj = x2js.xml_str2json( xmlText );
84 console.log(jsonObj.MyArrays.test2.item[0]);
85 ```
86  
87 ## Or using the utility function
88  
89 ```
90 var x2js = new X2JS();
91 var xmlText = "<MyArrays>"+
92 "<test><item>success</item><item>second</item></test>"+
93 "</MyArrays>";
94 var jsonObj = x2js.xml_str2json( xmlText );
95 console.log(x2js.asArray(jsonObj.MyArrays.test.item)[0]);
96 ```
97  
98 # Working with XML attributes
99  
100 ## Accessing to XML attributes
101  
102 ```
103 // Create x2js instance with default config
104 var x2js = new X2JS();
105  
106 var xmlText = "<MyOperation myAttr='SuccessAttrValue'>MyText</MyOperation>";
107 var jsonObj = x2js.xml_str2json( xmlText );
108  
109 // Access to attribute
110 console.log(jsonObj.MyOperation._myAttr);
111  
112 // Access to text
113 console.log(jsonObj.MyOperation.__text);
114 // Or
115 console.log(jsonObj.MyOperation.toString());
116 ```
117  
118 ## Configuring a custom prefix to attributes
119  
120 ```
121 var x2js = new X2JS({
122 attributePrefix : "$"
123 });
124  
125 var xmlText = "<MyOperation myAttr='SuccessAttrValue'>MyText</MyOperation>";
126  
127 var jsonObj = x2js.xml_str2json( xmlText );
128  
129 // Access to attribute
130 console.log(jsonObj.MyOperation.$myAttr);
131 ```
132  
133 # Working with XML namespaces
134  
135 ## Parsing XML with namespaces
136  
137 ```
138 var xmlText = "<testns:MyOperation xmlns:testns='http://www.example.org'>"+
139 "<test>Success</test><test2 myAttr='SuccessAttrValueTest2'>"+
140 "<item>ddsfg</item><item>dsdgfdgfd</item><item2>testArrSize</item2></test2></testns:MyOperation>";
141  
142 var jsonObj = x2js.xml_str2json( xmlText );
143 console.log(jsonObj.MyOperation.test);
144 ```
145  
146 ## Creating JSON (for XML) with namespaces (Option 1)
147  
148 ```
149 var testObjC = {
150 'm:TestAttrRoot' : {
151 '_tns:m' : 'http://www.example.org',
152 '_tns:cms' : 'http://www.example.org',
153 MyChild : 'my_child_value',
154 'cms:MyAnotherChild' : 'vdfd'
155 }
156 }
157  
158 var xmlDocStr = x2js.json2xml_str(
159 testObjC
160 );
161 ```
162  
163 ## Creating JSON (for XML) with namespaces (Option 2)
164  
165 ```
166 // Parse JSON object constructed with another NS-style
167 var testObjNew = {
168 TestAttrRoot : {
169 __prefix : 'm',
170 '_tns:m' : 'http://www.example.org',
171 '_tns:cms' : 'http://www.example.org',
172 MyChild : 'my_child_value',
173 MyAnotherChild : {
174 __prefix : 'cms',
175 __text : 'vdfd'
176 }
177 }
178 }
179  
180 var xmlDocStr = x2js.json2xml_str(
181 testObjNew
182 );
183 ```
184  
185 # Working with XML DateTime
186  
187 ## Configuring it beforehand
188  
189 ```
190 var x2js = new X2JS({
191 datetimeAccessFormPaths : [
192 "MyDts.testds" /* Configure it beforehand */
193 ]
194 });
195  
196 var xmlText = "<MyDts>"+
197 "<testds>2002-10-10T12:00:00+04:00</testds>"+
198 "</MyDts>";
199 var jsonObj = x2js.xml_str2json( xmlText );
200 ```
201  
202 ## Or using the utility function
203  
204 ```
205 var x2js = new X2JS();
206  
207 var xmlText = "<MyDts>"+
208 "<testds>2002-10-10T12:00:00+04:00</testds>"+
209 "</MyDts>";
210 var jsonObj = x2js.xml_str2json( xmlText );
211  
212 console.log(x2js.asDateTime( jsonObj.MyDts.testds ));
213 ```
214  
215 # Networking samples
216  
217 ## Parsing AJAX XML response (JQuery sample)
218  
219 ```
220 $.ajax({
221 type: "GET",
222 url: "/test",
223 dataType: "xml",
224 success: function(xmlDoc) {
225 var x2js = new X2JS();
226 var jsonObj = x2js.xml2json(xmlDoc);
227  
228 }
229 });
230 ```
231  
232 ## Loading XML and converting to JSON
233  
234 ```
235 function loadXMLDoc(dname) {
236 if (window.XMLHttpRequest) {
237 xhttp=new XMLHttpRequest();
238 }
239 else {
240 xhttp=new ActiveXObject("Microsoft.XMLHTTP");
241 }
242 xhttp.open("GET",dname,false);
243 xhttp.send();
244 return xhttp.responseXML;
245 }
246  
247  
248 var xmlDoc = loadXMLDoc("test.xml");
249 var x2js = new X2JS();
250 var jsonObj = x2js.xml2json(xmlDoc);
251 ```
252