nashwaan / xml-js Goto Github PK
View Code? Open in Web Editor NEWConverter utility between XML text and Javascript object / JSON text.
License: MIT License
Converter utility between XML text and Javascript object / JSON text.
License: MIT License
When supplying a value for standalone
in _declaration
attributes I get TS error:
Object literal may only specify known properties, and 'standalone' does not exist in type '{ version?: string | number | undefined; encoding?: string | number | undefined; } | undefined'.
Not sure if there are any other valid props.
Hello, this is most likely not an issue but a request for support. However, I don't see other ways to request support in this case. I want to use the npm package xml-js in Angular 2 and use SystemJS as the package loader. I haven't been able to get this working. I can experiment with xml-js in a node-script. That works fine. But the "require" statement that works so good in node scripts has to be replaced by something else. Something in TypeScript with which to instruct SystemJS to load the package I suppose. Advice would be highly appreciated. Jan Verheul ([email protected]).
sample xml:
<test><!----></test>
output:
{
"elements": [
{
"type": "element",
"name": "test-child"
}
]
}
expected output:
{
"elements": [
{
"type": "element",
"name": "test-child",
"elements": [
{
"type": "comment",
"comment": ""
}
]
}
]
}
Is there an option to do this?
I'm running version 0.9.7. This works:
> var convert = require('xml-js');
> convert.xml2js('<?xml version="1.0" encoding="utf-8"?>')
{ declaration: { attributes: { version: '1.0', encoding: 'utf-8' } } }
But the same fails with single quotes for the attributes:
> convert.xml2js("<?xml version='1.0' encoding='utf-8'?>")
{ declaration: { attributes: { undefined: undefined } } }
I haven't found a formal reference, but from forum posts it sounds like both single or double quotes should be valid for declarations.
Thanks!
How can I use it with angular 2+???????
๐ I've been using this library extensively without any issues! Great job!
@nashwaan close this issue when you've read this ๐ค
Hi,
Can you guide me how can I find why the conversion returns an empty object? There is no error that can give me a hint what is the problem...
Please see this code:
https://runkit.com/niktv/5ad4fad6772a1e00129ebe64
Thanks,
Nik
Hi ,
I am trying to convert xml data to json and after some processing i want to convert back to xml. For testing purpose i am converting below data which is part of my xml file.
<ProfAlign name="Layout">
<PVI>0.77.906</PVI>
<ParaCurve length="200.">247.13 91.807</ParaCurve>
<PVI>1658.62622142 104.85033164</PVI>
</ProfAlign>
xml2json ({compact: true, spaces: 4}) converts this data as below,
"ProfAlign": [
{
"_attributes": {
"name": "Layout"
},
"PVI": [
{
"_text": "0. 77.906"
},
{
"_text": "1658.62622142 104.85033164"
}
],
"ParaCurve": {
"_attributes": {
"length": "200."
},
"_text": "247.13 91.807"
}
}
And json2xml ({indentAttributes: false, spaces: '\t', fullTagEmptyElement: true, compact: true}) converts back to xml like below,
<ProfAlign name="Layout">
<PVI>0.77.906</PVI>
<PVI>1658.62622142 104.85033164</PVI>
<ParaCurve length="200.">247.13 91.807</ParaCurve>
</ProfAlign>
As you can see, order is changed. Please suggest how to handle this.
Hi,
I am trying to parse json to xml (both in code with json2xml
and with cli), but it gives me this error:
/Users/.../node_modules/xml-js/lib/js2xml.js:35
return (!firstLine && options.spaces ? '\n' : '') + Array(depth + 1).join(options.spaces);
^
RangeError: Maximum call stack size exceeded
at Array.join (native)
at writeIndentation (/Users/.../node_modules/xml-js/lib/js2xml.js:35:74)
at writeElementsCompact (/Users/.../node_modules/xml-js/lib/js2xml.js:225:37)
at writeElementCompact (/Users/.../node_modules/xml-js/lib/js2xml.js:204:12)
at writeElementsCompact (/Users/.../node_modules/xml-js/lib/js2xml.js:225:83)
at writeElementCompact (/Users/.../node_modules/xml-js/lib/js2xml.js:204:12)
at writeElementsCompact (/Users/.../node_modules/xml-js/lib/js2xml.js:225:83)
at writeElementCompact (/Users/.../node_modules/xml-js/lib/js2xml.js:204:12)
at writeElementsCompact (/Users/.../node_modules/xml-js/lib/js2xml.js:225:83)
at writeElementCompact (/Users/.../node_modules/xml-js/lib/js2xml.js:204:12)
at writeElementsCompact (/Users/.../node_modules/xml-js/lib/js2xml.js:225:83)
at writeElementCompact (/Users/.../node_modules/xml-js/lib/js2xml.js:204:12)
at writeElementsCompact (/Users/.../node_modules/xml-js/lib/js2xml.js:225:83)
at writeElementCompact (/Users/.../node_modules/xml-js/lib/js2xml.js:204:12)
at writeElementsCompact (/Users/.../node_modules/xml-js/lib/js2xml.js:225:83)
at writeElementCompact (/Users/.../node_modules/xml-js/lib/js2xml.js:204:12)
The original json file is:
{
"vertical": {
"-display_name": "Exercise",
"html": { "-url_name": "12345" },
"lti_consumer": {
"-url_name": "12345",
"-xblock-family": "xblock.v1",
"-accept_grades_past_due": "false",
"-weight": "14.0",
"-has_score": "true",
"-display_name": "Exercise",
"-ask_to_send_username": "true",
"-ask_to_send_email": "true",
"-button_text": "Launch Exercise",
"-custom_parameters": "none",
"-lti_id": "id",
"-launch_target": "new_window",
"-launch_url": "url"
}
}
}
I would be grateful for any insights!
Thanks!
Yve
I haven't tried all of the XML libraries, but this is by far the best one I've seen.
I'd like to add a Typescript definition to this project, it will take me a while before understanding your top level schema, but so far it's very clean!
Adding JSDocs to the functions really help out as well.
There's two approaches:
Once I get something up and running, I'd like for you @nashwaan to review it, Typescript definitions are pretty straightforward.
I've written a few before, have a look at these examples:
https://gist.github.com/DenisCarriere/11415dc23d5cab134180e86c07f06ae3
WARNING in ./node_modules/xml-js/node_modules/sax/lib/sax.js
Module not found: Error: Can't resolve 'stream' in '/home/xxx/xxx/xxx/my-app/node_modules/xml-js/node_modules/sax/lib'
Hi,
In my application I run user scripts in a Node VM. I added your library to provide easy XML parsing and generation capabilities. Now I run into a problem when I try to convert an Array
to XML. The array is created within the user script which runs in a sandbox context. The library is added to this context, but uses the wrapping context itself.
As far as I can tell, the problem are the instanceof Array
checks in your conversion code. Because I have now two different versions of the Array
object (one in each context) the check doesn't work anymore. See also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof
Reusing the same context is currently not possible for me as the scripts have to run in a sandbox with limited access.
I created a test case that illustrates the problem:
var convert = require("../lib");
var Script = require("vm").Script;
describe("case by silentgert", function() {
var context = {
convert: convert,
output: undefined,
};
var scriptCode =
"(function() {\n" +
" const obj = {\n" +
" customers : {\n" +
" customer: [\n" +
" {\n" +
" _text: 'John Doe',\n" +
" _attributes: {\n" +
" status: 'silver'\n" +
" }\n" +
" },\n" +
" {\n" +
" _text: 'Alice Allgood',\n" +
" _attributes: {\n" +
" status: 'gold'\n" +
" }\n" +
" }\n" +
" ]\n" +
" }\n" +
" };\n" +
" output = convert.js2xml(obj, { compact: true });\n" +
"})()\n";
var executableScript = new Script(scriptCode, {
displayErrors: true,
});
it ('should convert Arrays in a different context', function() {
executableScript.runInNewContext(context);
expect(context.output).toEqual('<customers><customer status="silver">John Doe</customer><customer status="gold">Alice Allgood</customer></customers>');
});
});
Expect outcome:
<customers>
<customer status="silver">John Doe</customer>
<customer status="gold">Alice Allgood</customer>
</customers>
Observed outcome:
<customers>
<customer>
<0 status="silver">John Doe</0>
<1 status="gold">Alice Allgood</1>
</customer>
</customers>
Possible solution:
In the Mozilla docs they mention to use Array.isArray
for secure checks. Another option might be to look at how Lodash is doing the isArray
check (without adding the dependency).
If you are okay with it, I can look into the issue and provide a pull request.
Hey,
I apologize if this is posted in the wrong place, but looking at the Quick Start example we have
var convert = require('xml-js');
var xml =
'<?xml version="1.0" encoding="utf-8"?>' +
'<note importance="high" logged="true">' +
' <title>Happy</title>' +
' <todo>Work</todo>' +
' <todo>Play</todo>' +
'</note>';
var op = { compact: true, spaces: 4 };
var result1 = convert.xml2json(xml, op);
console.log(result1);
Converting back,
console.log(convert. json2xml(result1, op));
Which gives the following error:
json2xml.js:4 Uncaught ReferenceError: Buffer is not defined
Other than what's up there, I grabbed xml-js through
npm install --save xml-js
Thoughts?
Hi, I'm trying to get a Json from an XML file.
It works with the given XML code:
var xml =
'' +
'' +
' <title>Happy</title>' +
' Work' +
' Play' +
'';
But it doesn't with my local xml file
var xml = require('./pregunta.xml')
This is the content:
Moodle QUIZ XML export ยญSi un coche circula a 25m/s... ยญLo hace a 90km/h true false ยญSi un coche circula a 25m/s... ยญLo hace a 50m/min true false ยญSi un coche circula a 25m/s... ยญLo hace a 80km/h true falseI get the following error:
Error: Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
|
|
|
Could you please help me?
Thanks.
I would like the option of getting the following output, with each attribute on a separate line with indentation
<parent
bar=1
baz="hello"
>
<child
attr1="a"
attr2="b"
/>
</parent>
// test.js
const convert = require('xml-js');
const js = { request: { user: 'username', pass: 'password', numbers: { number: 1, number: 2 } } }
const xml = convert.js2xml(js);
console.log(xml);
> node test.js
''
[email protected]
[email protected]
runkit here - https://runkit.com/jncr/xml-js. Something I'm doing wrong?
Also, xml2json crashes if it encounters an unescaped <, >, or & in the XML, but I am not sure whether you would consider that a bug.
Input:
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>xml-js</to>
<from>ACraig</from>
<heading>Min Example</heading>
<body>Here are some characters that get sanitized: " '</body>
</note>
Code:
var fs = require('fs');
var converter = require('xml-js');
fs.readFile('minexample.xml', 'utf8', function(err, xml) {
if (err) throw err;
console.log('XML:');
console.log(xml);
console.log('compact JSON:');
var json1 = converter.xml2json(xml, {compact: true, spaces: 2});
console.log(json1);
console.log('back-converted XML from compact:');
xmlback1 = converter.json2xml(json1, {compact: true, spaces: 2, sanitize: false});
console.log(xmlback1);
console.log('matches original:');
console.log(xmlback1 == xml);
fs.writeFile('backfromcompact.xml', xmlback1, function(err) {
if(err) {
return console.log(err);
}
console.log('Saved backfromcompact.xml.');
});
console.log('verbose JSON:');
var json2 = converter.xml2json(xml, {compact: false, spaces: 2});
console.log(json2);
console.log('back-converted XML from verbose:');
xmlback2 = converter.json2xml(json2, {compact: false, spaces: 2, sanitize: false});
console.log(xmlback2);
console.log('matches original:');
console.log(xmlback2 == xml);
fs.writeFile('backfromverbose.xml', xmlback2, function(err) {
if(err) {
return console.log(err);
}
console.log('Saved backfromverbose.xml.');
});
});
Output:
XML:
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>xml-js</to>
<from>ACraig</from>
<heading>Min Example</heading>
<body>Here are some characters that get sanitized: " '</body>
</note>
compact JSON:
{
"_declaration": {
"_attributes": {
"version": "1.0",
"encoding": "UTF-8"
}
},
"note": {
"to": {
"_text": "xml-js"
},
"from": {
"_text": "ACraig"
},
"heading": {
"_text": "Min Example"
},
"body": {
"_text": "Here are some characters that get sanitized: \" '"
}
}
}
back-converted XML from compact:
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>xml-js</to>
<from>ACraig</from>
<heading>Min Example</heading>
<body>Here are some characters that get sanitized: " '</body>
</note>
matches original:
false
verbose JSON:
{
"declaration": {
"attributes": {
"version": "1.0",
"encoding": "UTF-8"
}
},
"elements": [
{
"type": "element",
"name": "note",
"elements": [
{
"type": "element",
"name": "to",
"elements": [
{
"type": "text",
"text": "xml-js"
}
]
},
{
"type": "element",
"name": "from",
"elements": [
{
"type": "text",
"text": "ACraig"
}
]
},
{
"type": "element",
"name": "heading",
"elements": [
{
"type": "text",
"text": "Min Example"
}
]
},
{
"type": "element",
"name": "body",
"elements": [
{
"type": "text",
"text": "Here are some characters that get sanitized: \" '"
}
]
}
]
}
]
}
back-converted XML from verbose:
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>xml-js</to>
<from>ACraig</from>
<heading>Min Example</heading>
<body>Here are some characters that get sanitized: " '</body>
</note>
matches original:
false
Saved backfromcompact.xml.
Saved backfromverbose.xml.
Hello Please let me know of any changes in the configurations or options of the module.
It is not able to convert back the file of JSON to XML.
I'm getting extra white spaces when I'm using the text
elements when going two elements deep with compact=false
.
const Elements = {
type: 'element',
name: 'a',
elements: [{
type: 'element',
name: 'b',
elements: [{type: 'text', text: 'foo bar'}],
}]
}
const xml = convert.js2xml({ elements: [Elements] }, { compact: false, spaces: 4 })
console.log(xml)
xml output (notice 4 extra spaces after foo bar)
<a>
<b>foo bar </b>
</a>
Strange because when using compact=true
those spaces don't appear.
const Elements = {
a: {
b: {
_text: 'foo bar',
}
}
}
const xml = convert.js2xml(Elements, { compact: true, spaces: 4 })
console.log(xml)
xml output
<a>
<b>foo bar</b>
</a>
Hi, thanks for your great library!
xml-js version is v1.4.1
It seems that whitespace between two sibling elements is lost when converted if it is the only content. The following code illustrates the problem:
const convert = require('xml-js');
const xml = '<outer> This is <inner> some</inner> <inner>Text </inner> </outer>';
const json = convert.xml2json(xml, {compact: false, alwaysChildren: false});
const result = convert.json2xml(json, {compact: false});
console.log(result);
// <outer> This is <inner> some</inner><inner>Text </inner></outer>
As you can see, " This is " still has the whitespace after conversion, as well as " some " and " Text ", but not the whitespace between the first closing and second opening "inner" tags.
Is there some setting that I missed or is this a problem with the library?
Kind regards,
Daniel
If you use .xml2js (not .xml2json!) function with an XML file that contain following declaration:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
you get wrong declaration attributes (there will be extra attribute with name 'undefined' and value undefined).
In my debuging I found that the following code in lib/xml2js.js is producing that wrong result.
The reason is wrong RegExp used to parse next attribute name and value:
/([\w:-]+)\s*=\s*"([^"]*)"|'([^']*)'|(\w+)\s*/
The | (boolean OR) has priority so that regexp actually accepts (key=(spaces)"value") OR ('value') OR (value(spaces)).
The working regexp is, for example:
/([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\w+))\s*/
Code with wrong regexp (lib\xml2js.js):
if (instruction.body && (instruction.name.toLowerCase() === 'xml' || options.instructionHasAttributes)) { while (instruction.body) { var attribute = instruction.body.match(/([\w:-]+)\s*=\s*"([^"]*)"|'([^']*)'|(\w+)\s*/); if (!attribute) { break; } attributes[attribute[1]] = attribute[2]; instruction.body = instruction.body.slice(attribute[0].length); // advance the string } }
var convert = require('xml-js');
console.log(convert.json2xml(JSON.stringify({"name":'john'})));
console.log(convert.js2xml(JSON.stringify({"name":'john'})));
console.log(convert.json2xml({"name":'john'}));
console.log(convert.js2xml({"name":'john'}));
all are printing ""
I want to convert standard MLP (Mobile Positioning Protocol) xml to JSON and back.
Here is the first 3 line:
<svc_init ver="3.0.0">
After it is converted to JSON:
{
"_declaration": {
"_attributes": {
"version": "1.0",
"encoding": "UTF-8"
}
},
"svc_init": {
"_attributes": {
"ver": "3.0.0"
}
convert.xml2json(xml, { compact: true, spaces: 6, ignoreCdata: false });
I lost !DOCTYPE.
Can you add ignoreDoctype to the code?
Since true
and false
are expected to be boolean values, negating and/or testing explicitly failes.
XML
<a show="false"/>
to JSON
{
"a": {
"_attributes": {
"show": "false"
}
}
}
Testing
if (!a._attributes.show) // this is will not end well
Maybe I am missing something, but I believe xml2js
should be marked as returning Element | ElementCompact
and not just any
.
I don't know if this is easy to implement, but I am trying to do something like 'xml' -> json -> 'xml_1', and I want 'xml' and 'xml_1' to be exactly the same if I don't modify the intermediate 'json'.
Here is the problem. This is the original xml:
<source>
<x id="START_TAG_SPAN" ctype="x-span"/>Support and resistance<x id="CLOSE_TAG_SPAN" ctype="x-span"/> levels represent prices where there &
has been exhaustive supply or demand, which can influence the price if it approaches this level again. Support
acts like a floor: a price where investors tend to see good value, and heavy buying action keeps the price propped
up above this level. Some traders buy around support if they think it will hold. Others place stops just below
support, since a penetration suggests bearishness. Conversely, resistance acts like a ceiling: a price where
investors tend to take profits and the selling action holds the price below this level. Some investors take profits
near resistance if they think it will hold. Others place stops just above resistance, since a penetration suggests
bullishness.
</source>
After being converted to JavaScript Object and then back, the xml becomes:
<source>
<x id="START_TAG_SPAN" ctype="x-span"/>Support and resistance
<x id="CLOSE_TAG_SPAN" ctype="x-span"/> levels represent prices where there &
has been exhaustive supply or demand, which can influence the price if it approaches this level again. Support
acts like a floor: a price where investors tend to see good value, and heavy buying action keeps the price propped
up above this level. Some traders buy around support if they think it will hold. Others place stops just below
support, since a penetration suggests bearishness. Conversely, resistance acts like a ceiling: a price where
investors tend to take profits and the selling action holds the price below this level. Some investors take profits
near resistance if they think it will hold. Others place stops just above resistance, since a penetration suggests
bullishness.
</source>
You could see there is a newline before the SECOND <x>
node element. And I have no idea why there is another newline before </source>
I read the following XML with xml2json:
<?xml version="1.0"?>
<group>
<name><![CDATA[An example name]]></name>
</group>
but writing it back with json2xml gives me:
<?xml version="1.0"?>
<group>
<name>
<![CDATA[My modified name]]>
</name>
</group>
This is is not the expected XML output.
The CDATA section is not a TAG and should not be handled as one and therefore not be indented.
Sure, its easier to read, but its not 100% correct.
It would be great to fix that or make a config parameter for that behaviour.
example code:
var xmljs = require('xml-js');
var xmlIn = '<?xml version="1.0"?>\n<group>\n\t<name><![CDATA[An example name]]></name>\n</group>';
console.log('xmlIn:\n',xmlIn);
var jsonIn = xmljs.xml2json(xmlIn, {
compact: true
});
var obj = JSON.parse(jsonIn);
// code to modify obj
obj.group.name._cdata = 'My modified name';
var jsonOut = JSON.stringify(obj);
var xmlOut = xmljs.json2xml(jsonOut, {
compact : true,
spaces : 4,
fullTagEmptyElement: true
});
console.log('xmlOut:\n',xmlOut);
Solution
file: js2xml.js
case options.cdataKey: xml += writeCdata(element, options); break;
case options.cdataKey:
return false;
Releases stop at 1.6.0. Can you tag the 1.6.2 release?
making the fullTagEmptyElement in the options either true or false does not matter the tag always come abbreviated.
I am extending ElementCompact
and want to add some explicit optional properties:
export interface MyElement extends ElementCompact {
_attributes: {
id: string
doIEvenExist?: 'yes' | 'no'
}
}
Unfortunately with this I get TS error:
Property 'doIEvenExist' is incompatible with index signature.
Type '"yes" | "no" | undefined' is not assignable to type 'string | number'.
Type 'undefined' is not assignable to type 'string | number'.
I currently use the following workaround:
...
_attributes: ElementCompact['_attributes'] & {
...
When using xml2js
, this XML declaration is detected:
<?xml version="1.0" encoding="UTF-8"?>
Whilst this one, which I believe is legal, is not detected:
<?xml version='1.0' encoding='UTF-8'?>
Thank you for your good work!
This is not a functional error but the published format can be improved:
The input XML string:
<?xml version="1.0" encoding="utf-8" ?><l key="license_number_1"> <s id="Pharma HK Central" ip="xxxxxx0" port="yyyyyy0"/> <s id="Pharma Paris" ip="xxxxxx1" port="yyyyyy1"/> <s id="Ph Bogota" ip="xxxxxx2" port="yyyyyy2"/></l>
The xml to JSON code:
let options = {
compact: true,
trim: true,
ignoreDeclaration: true,
ignoreComment: true,
alwaysChildren: false,
attributesKey: "$att",
textKey: "$val"
};
let jsonObj = xml_js.xml2json(xmlString, options);
console.log(JSON.stringify(jsonObj));
Conversion output:
"{"l":{"$att":{"key":"license_number_1"},"s":[{"$att":{"id":"Pharma HK Central","ip":"xxxxxx0","port":"yyyyyy0"}},{"$att":{"id":"Pharma Paris","ip":"xxxxxx1","port":"yyyyyy1"}},{"$att":{"id":"Ph Bogota","ip":"xxxxxx2","port":"yyyyyy2"}}]}}"
Expected:
{"l":{"$att":{"key":"license_number_1"},"s":[{"$att":{"id":"Pharma HK Central","ip":"xxxxxx0","port":"yyyyyy0"}},{"$att":{"id":"Pharma Paris","ip":"xxxxxx1","port":"yyyyyy1"}},{"$att":{"id":"Ph Bogota","ip":"xxxxxx2","port":"yyyyyy2"}}]}}
Of course, the backslah before double quotes make sense because of the output string's leading and trailing double quotes, and, again, it doesn't affect the correct use of the JSON object.
But it would be more readable to have the clean output, other alike packages, less functional than 'xml-js' do it.
I installed running version 1.4.2 and tried to run one of the examples from the npm site .
Here's the code that I've been trying to run w/o success. Only seem to work xml > js and not the other way around.
var options = {
spaces: 3,
compact: false,
fullTagEmptyElement: true,
ignoreDeclaration: false,
ignoreInstruction: false,
ignoreAttributes: false
};
var xml =
'' +
'' +
' <title>Happy</title>' +
' Work' +
' Play' +
'';
var someJs = {"a":{"_text":"Hi There"}};
// works as expected
var result1 = convert.xml2js(xml, {compact: true, spaces: 4});
// doesn't work - only returns empty string
var restult2 = convert.js2xml(someJs, options);
We can introduce an option to directly show the corresponding XML value instead of showing it under _text
.
Eg.
XML:
<key1>value1</key1>
<key2>value2</key2>
COMPACT JS-OBJECT:
{
key1: {_text: "value1"},
key2: {_text: "value2"}
}
With the new option:
{
key1: "value1",
key2: "value2"
}
For my own usage, I used this recursive workaround for the same, hence thought for the enhancement : https://github.com/noveens/js-owncloud-client/pull/19/files#diff-b9b823e719730e39048dffbb512e743cR777
Thanks.
Pardon me if that question is very poorly worded.
Basically I have an XML document where each XML element has attributes, but no child elements. So it's safe to skip the creation of an _attributes
object. The attributes themselves can go right on the generated JSON object.
Example: Given
<a val="5"/>
<a val="6"/>
I'd like the output to be (Note, I can make a
plural myself as in this example)
{
"as": [
{
"val": "5"
},
{
"val": "6"
}
]
}
rather than
{
"a": [
{
"_attributes": {
"val": "5"
}
},
{
"_attributes": {
"val": "6"
}
}
]
}
To reproduce, I've first made an XML file that looks similar to what I'm looking for :
<ZohoCreator>
<applicationslist>
<application name="testapp">
<formlist>
<form name="Untitled_Form">
<add>
<field name="Subform_Single_Line">
<value>Value1</value>
</field>
</add>
</form>
<form name="Untitled_Form">
<add>
<field name="Subform_Single_Line">
<value>Value2</value>
</field>
</add>
</form>
</formlist>
</application>
<application name="derp">
<formlist>
</formlist>
</application>
</applicationslist>
</ZohoCreator>
Which gave me this :
{
"ZohoCreator": {
"applicationslist": {
"application": [
{
"_attributes": {
"name": "testapp"
},
"formlist": {
"form": [
{
"_attributes": {
"name": "Untitled_Form"
},
"add": {
"field": {
"_attributes": {
"name": "Subform_Single_Line"
},
"value": {
"_text": "Value1"
}
}
}
},
{
"_attributes": {
"name": "Untitled_Form"
},
"add": {
"field": {
"_attributes": {
"name": "Subform_Single_Line"
},
"value": {
"_text": "Value2"
}
}
}
}
]
}
},
{
"_attributes": {
"name": "derp"
},
"formlist": {}
}
]
}
}
}
So far so good. Now that I've got a well-formatted json according to your library's needs, let's try parsing it again, but backwards this time!
<ZohoCreator>
<applicationslist>
<application>
<0 name="testapp">
<formlist>
<form>
<0 name="Untitled_Form">
<add>
<field name="Subform_Single_Line">
<value>Value1</value>
</field>
</add>
</0>
<1 name="Untitled_Form">
<add>
<field name="Subform_Single_Line">
<value>Value2</value>
</field>
</add>
</1>
</form>
</formlist>
</0>
<1 name="derp">
<formlist/>
</1>
</application>
</applicationslist>
</ZohoCreator>
Yeah. It's nothing like what we got. This is kinda killing it for me, as I was trying to convert a JSON into an XML in a easier fashion.
If the attribute is a number attributes[key].replace is not a function
is fired fired.
Line 45 in ea88577
When there is not the option attribute compact: true,
neither js2xml nor json2xml work, they return instead undefined
Hello!
I have a array objects.
[ { type: 'element', name: 'material', elements: [ [Object] ] },
{ type: 'element', name: 'material', elements: [ [Object] ] },
{ type: 'element', name: 'material', elements: [ [Object] ] },
{ type: 'element', name: 'material', elements: [ [Object] ] },
{ type: 'element', name: 'material', elements: [ [Object] ] } ]
And after convert I getting the next xml
<material><mattext><p><font size="14"><strong>....</material>
<material><mattext><p><font size="14"><strong>....</material>
But if execute xml2json
for result above then, I receive the error.
Error: Text data outside of root node.
Line: 248
Column: 26
Could you tell me how I can insert root node ?
Thanks very much for this very useful library. I've run into an issue since ampersands in XML attributes aren't being escaped by js2xml. This seems to have happened after the change described here: #26 (comment) however the StackOverflow answer that is referenced seems to be incorrect or just very badly structured? The spec extract that is quoted seems to contradict its recommendation and attributes with ampersands don't validate properly - e.g. try https://validator.w3.org/check with
<?xml version="1.0"?>
<elt attr="abc&def"></elt>
"title": {
"_text": "You Won't Believe What These 31 Oscar Winners Look Like Now"
},
Hi there, I have a use case where the XML is not fixed, it can be anything according to a certain spec.
At the moment I am looking for a specific property, let's take the following examples:
<d:multistatus xmlns="DAV:">
<response>
<href>/</href>
<propstat>
<prop>
<current-user-principal>
<href>/principals/users/johndoe/</href>
</current-user-principal>
</prop>
<status>HTTP/1.1 200 OK</status>
</propstat>
</response>
</d:multistatus>
<d:multistatus xmlns:d="DAV:">
<d:response>
<d:href>/</d:href>
<d:propstat>
<d:prop>
<d:current-user-principal>
<d:href>/principals/users/johndoe/</d:href>
</d:current-user-principal>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
</d:response>
</d:multistatus>
You see one time I get the XML with a global namespace defined to "DAV:" making all elements part of that namespace and the other time theres a namespace of "d" that maps the "d:" to "DAV:".
When I check the JSON object for existence of "d:multistatus", it will return false on the first part of xml while there actually is a "multistatus" element. What I would like to see is that every element in the XML is prefixed by the namespace. So that in both above cases, the elements are called "DAV:multistatus" instead of "d:multistatus" or just "multistatus".
I hope you know what I mean, and can help me with this problem. Maybe there is already a way to get the elements correctly respecting the namespaces.. I'd like to hear from you :)
E.g.
{
type: 'element',
name: 'root',
attributes: { 'target-attr': '"' }
}
is converted to invalid xml
<root attr=""" />
instead of
<root attr=""" />
A PR is on the way ๐
XML - >
<?xml version="1.0" encoding="utf-8"?>
<dp:ListServicesReply ReturnCode="0" xmlns:dp="http://www.cisco.com/vtg/diagnosticportal">
<dp:Schema Version="1.0" />
<dp:ServiceList>
<dp:Service Name="Cisco ICM usgd1 LoggerA" Description="Provides Call Logging services for Instance usgd1" Status="Running" StartupType="Auto" LogOnAs="****" />
<dp:Service Name="Cisco ICM Diagnostic Framework" Description="Provides a web-based diagnostic service for Cisco Unified ICM, Contact Center Enterprise application." Status="Running" StartupType="Auto" LogOnAs="LocalSystem" />
</dp:ServiceList>
</dp:ListServicesReply>
Getting this stack when attempting to parse the above XML doc
/node_modules/sax/lib/sax.js:984
throw this.error
^
Error: Text data outside of root node.
Line: 0
Column: 15
Char: ]
at error (./node_modules/sax/lib/sax.js:667:10)
at strictFail (./node_modules/sax/lib/sax.js:693:7)
at Object.write (./node_modules/sax/lib/sax.js:1048:15)
at module.exports (./node_modules/xml-js/lib/xml2js.js:226:16)
at Object.module.exports as xml2json
at Object. (./portico.js:27:23)
at Module._compile (module.js:556:32)
at Object.Module._extensions..js (module.js:565:10)
at Module.load (module.js:473:32)
at tryModuleLoad (module.js:432:12)
From README:
Portable Code: Written purely in JavaScript which means it can be used in Node environment and browser environment (via bundlers like browserify/JSPM/Webpack).
It cannot be fully bundled for browsers because SAX requires Node's built-in packages 'Stream' and 'string_decoder' (https://github.com/isaacs/sax-js/blob/master/lib/sax.js#L233)
I have XML files that are exported from Excel and have XMLNS prefix data. I don't need to use the data and it's awkward to use objects created with colons in the key.
The fix that meets my needs is simply to add this line at line 140 of xml2js.js:
name = name.slice ( name.search ( ':' ) + 1 ) ;
I suspect a full implementation would be more work and I'm happy to do that and propose a check-in if you'd like.
I use some optional attributes that I want to render only when they are set.
When some of them are undefined, current xml output is myAttr="undefined"
, which makes the document not valid.
My current workaround is to use lodash
with
{
_arguments: pickBy({
someProp: 'fixed',
otherProp1: optionalValue1,
...
otherPropN: optionalValueN,
})
}
I have an XML document that includes a processing instruction. But when I run it through xml2js, the processing instruction gets left behind.
<?xml version="1.0"?>
<?myapi version="13.0"?>
I recently switched to this Node package for its versatility and I'm loving it. However, one thing I was missing is an option to format the XML output when using js2xml()
. Consider the following example.
1.) Input object:
var obj = {
_comment: " Released under The MIT License ",
snippet: {
content: {
_cdata: "console.log($1)"
},
tabTrigger: {
_text: "log"
},
scope: {
_text: "source.js"
}
}
};
2.) Output XML โ convert.json2xml(obj, {compact: true})
:
<!-- Released under The MIT License --><snippet><content><![CDATA[console.log($1)]]></content><tabTrigger>log</tabTrigger><scope>source.js</scope></snippet>
3.) Output XML โ convert.json2xml(obj, {compact: false, spaces: 4})
:
<!-- The MIT License -->
<snippet>
<content/>
<tabTrigger/>
<scope/></snippet>
The output in 2.) is technically valid, but I would prefer an option that produces tidy/beautified XML. Unless I did something wrong, adding the spaces: 4
options produces an undesired result, why is both _cdata
and _text
missing?
Expected result (also note the indentation):
<!-- The MIT License -->
<snippet>
<content><![CDATA[console.log($1)]]></content>
<tabTrigger>log</tabTrigger>
<scope>source.js</scope>
</snippet>
Not sure whether this is a bug or a misunderstanding of mine.
PS: I also tried converting the object to JSON with pretty-print and then use json2xml()
instead โ the results are the same!
Just noticed that your published npm bundle is pretty large, almost 1MB (824KB).
$ du -h node_modules/xml-js
184K xml-js/artwork
12K xml-js/bin
32K xml-js/lib
156K xml-js/test/browse-jasmine/lib/jasmine-2.5.2
156K xml-js/test/browse-jasmine/lib
452K xml-js/test/browse-jasmine
520K xml-js/test
824K xml-js
$ ls -lh
-rw-r--r-- 1 mac staff 1.1K May 2 2016 LICENSE
-rw-r--r-- 1 mac staff 17K Nov 4 00:15 README.md
-rw-r--r-- 1 mac staff 456B Jun 7 2016 appveyor.yml
drwxr-xr-x 5 mac staff 170B Jan 24 10:07 artwork
drwxr-xr-x 4 mac staff 136B Jan 24 10:07 bin
-rw-r--r-- 1 mac staff 34B Sep 7 03:42 index.js
drwxr-xr-x 8 mac staff 272B Jan 24 10:07 lib
-rw-r--r-- 1 mac staff 5.2K Jan 24 10:07 package.json
drwxr-xr-x 13 mac staff 442B Jan 24 10:07 test
Your core javascript files (index.js
+ lib/
) is only 32KB.
Inside your test cases you've got 520KB that you ship with your npm bundle also artwork
is 180KB, might be worth adding an .npmignore
file to your repo and exclude some of the files that are not needed.
**Proposed .npmignore
artwork/
test/
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.