Giter VIP home page Giter VIP logo

fast-xml-parser's Introduction

Known Vulnerabilities NPM quality Coverage Status Try me NPM total downloads

Validate XML, Parse XML to JS Object, or Build XML from JS Object without C/C++ based libraries and no callback.

XML Parser v5 is added for experimental use https://solothought.com

Sponsor this project 👉 Stubmatic donate button

Current Sponsors

Check the complete list at ThankYouBackers for our sponsors and supporters.

Through Github

Through OpenCollective

Users

Check the bigger list

The list of users is collected either from the list published by Github, communicated directly through mails/chat , or from other resources. If you feel that your name in the above list is incorrectly published or you're not the user of this library anymore then you can inform us to remove it. We'll do the necessary changes ASAP.

If you want to be an anonymous user of this application and don't want to be highlighted anywhere then you can contact me at

Main Features

FXP logo

  • Validate XML data syntactically
  • Parse XML to JS Object
  • Build XML from JS Object
  • Works with node packages, in browser, and in CLI (press try me button above for demo)
  • Faster than any other pure JS implementation.
  • It can handle big files (tested up to 100mb).
  • Controlled parsing using various options
  • XML Entities, HTML entities, and DOCTYPE entites are supported.
  • unpaired tags (Eg <br> in HTML), stop nodes (Eg <script> in HTML) are supported.
  • You can restore almost same XML from JSON
  • Supports comments
  • It can preserve Order of tags in JS object
  • You can control if a single tag should be parsed into array.
  • Supports parsing of PI (Processing Instruction) tags with XML declaration tags
  • And many more other features.

v5

I developed v5 in Apr 2023. And I didn't get the chance to complete all the features. I've ensured that new features don't impact performance. With v5, you have more control on parsing output. Check docs for syntax help and basic understanding.

Please leave a comment in discussion forum for your suggestions and if you really need v5.

How to use

To use as package dependency $ npm install fast-xml-parser or $ yarn add fast-xml-parser

To use as system command $ npm install fast-xml-parser -g

To use it on a webpage include it from a CDN

Example

As CLI command

$ fxparser some.xml

In a node js project

const { XMLParser, XMLBuilder, XMLValidator} = require("fast-xml-parser");

const parser = new XMLParser();
let jObj = parser.parse(XMLdata);

const builder = new XMLBuilder();
const xmlContent = builder.build(jObj);

In a HTML page

<script src="path/to/fxp.min.js"></script>
:
<script>
  const parser = new fxparser.XMLParser();
  parser.parse(xmlContent);
</script>

Check lib folder for different browser bundles

Bundle Name Size
fxbuilder.min.js 5.2K
fxparser.js 50K
fxparser.min.js 17K
fxp.min.js 22K
fxvalidator.min.js 5.7K

Documents

v3

v4

  1. GettingStarted.md
  2. XML Parser
  3. XML Builder
  4. XML Validator
  5. Entities
  6. HTML Document Parsing
  7. PI Tag processing

Performance

XML Parser

  • Y-axis: requests per second
  • X-axis: File size

Large files

  • Y-axis: requests per second
  • X-axis: File size

XML Builder

  • Y-axis: requests per second

negative means error

Supporters

Contributors

This project exists thanks to all the people who contribute. [Contribute].

Backers

Thank you to all our backers! 🙏 [Become a backer]

License

  • MIT License

Donate $5

fast-xml-parser's People

Contributors

alfonsomunozpomer avatar amitguptagwl avatar bb avatar delagen avatar dependabot[bot] avatar erkie avatar gei0r avatar j0k3r avatar josep11 avatar karlbecker avatar kurtpreston avatar lplazas avatar massimo-ua avatar monkeywithacupcake avatar nhuethmayr avatar orgads avatar robhaj avatar sarahdayan avatar serggonin avatar squitchyt avatar sverweij avatar tatsh avatar thedeathconqueror avatar tomasbruckner avatar tomldev avatar tomsseisums avatar trentshell avatar werehamster avatar yakov116 avatar zshare avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fast-xml-parser's Issues

xml2js: Accept standard input

Typical command line feature. Very handy with responses from another tool like cURL instead of having to save files before passing to xml2js. Accept - as the argument for stdin (or check isatty() and read standard input if that returns false).

Right now it can be done in Bash like so:

xml2js <(some command that prints XML string)

# Example
xml2js <(some command that prints XML string) | jq -S '.cool_stuff|here'

Not too bad but this would be easier to type and infer from:

some command that prints XML string | xml2js -

CDATA parsing

Hi - Following CDATA in XML fails to convert correctly in JSON.

Ping of Death or Smurf attacks.

However, you should never filter ALL ICMP messages, as some of them ("Don't Fragment", "Destination Unreachable", "Source Quench", etc) are necessary for proper behavior of Operating System TCP/IP stacks.

It may be wiser to contact your network consultants for advice, since this issue impacts your overall network reliability and security. ]]>

The output I get is

"solution":{"I":["Ping of Death","Smurf"],"P":{"B":"ALL","P":{}"DISCOVERY":{"REMOTE":1}}}

It doesn't parse empty attribute

Checklist

Please fill below checklist

  • Are you running the latest version? 3.2.0
  • Have you include sample input?
  • Have you include actual output?
  • Have you include expected output?
  • Have you checked if you are using correct configuration?
  • Did you try online tool?
  • Did you star the repository for further updates? ;)

Input data

<l ses="">
    <role>Administrator</role>
    A test value<role>Developer
    </role>
</l>

Code

    let options = {
        attributeNamePrefix: "",
        ignoreAttributes: false,
        //allowBooleanAttributes: true,
    };
     jsonObj = fastXmlParser.parse(xmlString, options);

Output data

{
    "l": {
        "role": [
            "Administrator",
            "Developer"
        ],
        "#text": "A test value"
    }
}

expected data

{
    "l": {
        "role": [
            "Administrator",
            "Developer"
        ],
        "ses": ""
        "#text": "A test value"
    }
}

Version 3.0.1 - wrong attribute parsing for "" value; no #text key ('Object' instead)

Important

If have some questions, please read the README or check spec folder for examples. Otherwise stackoverflow is the better place to discuss technical questions until or unless they are bug.

If you are raising a bug please fill it in following format to avoid long communication and fast resolution.

Checklist

Please fill below checklist

  • Are you running the latest version? 3.0.1
  • Have you include sample input?
  • Have you include actual output?
  • Have you include expected output?
  • Have you checked if you are using correct configuration?
  • Did you try online tool?
  • Did you star the repository for further updates? ;)

Input data

<l ses="">
    <role>Administrator</role>
    A test value<role>Developer
    </role>
</l>

Code

exports.xmlJsonParsing = function (xmlString) {

    // when a tag has attributes
    let options = {
        attributeNamePrefix: "",
        attrNodeName: false,
        textNodeName: "#text",
        ignoreAttributes: false,
        ignoreNameSpace: false,
        allowBooleanAttributes: true,
        parseNodeValue: true,
        parseAttributeValue: true,
        trimValues: true,
        decodeHTMLchar: true,
    };
    if (fastXmlParser.validate(xmlString) === true) {//optional
        jsonObj = fastXmlParser.parse(xmlString, options);
    }

    //Intermediate obj
    var tObj = fastXmlParser.getTraversalObj(xmlString, options);
    jsonObj = fastXmlParser.convertToJson(tObj, options);

    return jsonObj;
}

Output data

{"l":{"role":["Administrator","Developer"],"ses":true,"[object Object]":"A test value"}}

expected data

{"l":{"role":["Administrator","Developer"],"ses":"","#text":"A test value"}}

text with "leading-zero" result in wrong value

Hi, i faced an issue regarding the conversion of "date" and "time" values with leading zeros.

Given:

<?xml version="1.0"?>
<date>02082017</date>

Result:

{
    "date": 2082017
}

Expected:

{
    "date": "02082017"
}

I need the original, unprocessed values of the XML. So my idea would be, to have an option like "preserveTextNodeValues": true or "convertTextNodeValues": false to skip the value conversion and keep the original string value.

textNodeName consistency

Checklist

  • Are you running the latest version?
  • Include sample input XML
  • Include actual output
  • Include expected output
  • Did you try online tool?
  • Did you star the repository for further updates? ;)

I have the following input

<?xml version="1.0" encoding="UTF-8"?> <x id="1" cmd="init" ses=""> <i>A text inside 'i' tag<test id="999" name="new_user"/> </i> <j>Another inside 'j' tag</j> <k></k> </x>

Using the fast-xml-parser gives the following options:

'let options = {
attrPrefix: "attr_",
attrNodeName: true,
textNodeName: "text_",
ignoreNonTextNodeAttr: true,
ignoreTextNodeAttr: false,
ignoreNameSpace: false,
ignoreRootElement: false,
textNodeConversion: true,
textAttrConversion: false,
arrayMode: false
};'

and the output is:

'{"x":{"i":{"text_":"A text inside 'i' tag","test":{"true":{"attr_id":"999","attr_name":"new_user"}}},"j":"Another inside 'j' tag","k":""}}'

My question is: while the text inside the 'i' tag is marked with 'text_', the one inside the 'j' tag is not.
I expected to have, for the 'j' tag:
"j":{"text_":"Another inside 'j' tag"}

Thanks

[j2x]: attrNodeName invalid behavior

Checklist

Please fill below checklist

  • Are you running the latest version?
  • Have you include sample input?
  • Have you include actual output?
  • Have you include expected output?
  • Have you checked if you are using correct configuration?
  • Did you try online tool?
  • Did you bookmarked the repository for further updates? ;)

Input data

{
					root: {
						element:  {
							$: {
								aaa: "aaa",
								bbb: "bbb"
							},
							_: 1
						},
						element2: {
							$:          {
								aaa: "aaa2",
								bbb: "bbb2"
							},
							subelement: {$: {aaa: "sub_aaa"}}
						},
                                                date:"test"
					}
				}

Code

var options= {
	attributeNamePrefix: "",
	attrNodeName:        "$",
	textNodeName:        "_",
	ignoreAttributes:    false,
	cdataTagName:        "$cdata",
	cdataPositionChar:   "\\c",
	format:              false,
	indentBy:            "\t",
	supressEmptyNode:    true
};
var Parser = require("fast-xml-parser").j2xParser;
var result = new Parser(options).parse(obj);

Output data

<root date="test">
<element aaa="aaa" bbb="bbb" _="1"/>
<element2 aaa="aaa2" bbb="bbb2">
<subelement aaa="sub_aaa"/>
</element2>
</root>

expected data

<root>
<element aaa="aaa" bbb="bbb">1</element>
<element2 aaa="aaa2" bbb="bbb2">
<subelement aaa="sub_aaa"/>
</element2>
<date>test</date>
</root>

I think in j2x.js
should be as

function isAttribute(name/*, options*/) {
    if (!this.options.attrNodeName && name.startsWith(this.options.attributeNamePrefix)) {
        return name.substr(this.attrPrefixLen);
    } else {
        return false;
    }
}

or something else

Also condition should be removed in x2j due deprecation

if(options.decodeHTMLChar)
matches[i][4] = options.attrValueProcessor(matches[i][4]);

Two Attributes with quotes gives error

This issue is very similar to #58 but not exactly the same :

Checklist

  • Are you running the latest version? : 3.2.3
  • Have you include sample input?
  • Have you include actual output?
  • Have you include expected output?
  • Have you checked if you are using correct configuration?
  • Did you try online tool?
  • Did you bookmarked the repository for further updates? ;)

Input data

When I run the following code :

require('fast-xml-parser').validate(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><foo name="First'attribute"/><foo name="First'attribute"/>`)

I get :

{ err:
   { code: 'InvalidAttr',
     msg: 'attribute /><foo has no space in starting.' } }

I would expect the result to be a validationsuccess (return true)

It is allowed to have the single quote character if using double quotes as the delimiters (see https://stackoverflow.com/a/866894/1993501)

xmlns attribute omitted?

Checklist

Please fill below checklist

  • Are you running the latest version?
  • Have you include sample input?
  • Have you include actual output?
  • Have you include expected output?
  • Have you checked if you are using correct configuration?
  • Did you try online tool?
  • Did you star the repository for further updates? ;)

Input data

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"></project>

Code

online editor is enough to demonstrate bug

Output data

{
    "project": {
        "xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
        "xsi:schemaLocation": "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
    }
}

expected data

{
    "project": {
        "xmlns": "http://maven.apache.org/POM/4.0.0",
        "xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
        "xsi:schemaLocation": "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
    }
}

Removed whitespace at startup

Hi, in the getTraversalObj function, the blank spaces are removed at the beginning of the text. Sometimes these blanks are important, could you add this removal as optional in the options parameter?

Thank you very much.

var getTraversalObj =function (xmlData,options){
options = buildOptions(options);
xmlData = xmlData.replace(/>(\s+)/g, ">");//Remove spaces and make it single line. (THIS LINE)
var tags = getAllMatches(xmlData,tagsRegx);

Tag is not correct detected

Hi, i faced an issue regarding the detection of an custom tag.

Given:

<?xml version="1.0"?>
<tag.1>label 1</tag.1>
<tag.2>label 2</tag.2>

Result:

{
    "tag": [
        "label 1",
        "label 2"
    ]
}

Expected:

{
    "tag1": "label 1",
    "tag2": "label 2",
}

Is this expected behaviour? Because W3 said that the "." can be part of the tag name: https://www.w3.org/TR/2008/REC-xml-20081126/#d0e804

I suggest to enhance the tagsRegx with the allowed characters: ., :, _, -. (in this order)

getTraversalObj does not create a traversal object anymore

Checklist

Please fill below checklist

  • [x ] Are you running the latest version?
  • [ x] Have you include sample input?
  • [x ] Have you include actual output?
  • [x ] Have you include expected output?
  • [x ] Have you checked if you are using correct configuration?
  • Did you try online tool?
  • Did you bookmarked the repository for further updates? ;)

Input data

Please include your sample code here

const XML_PARSER_OPTIONS = {
attributeNamePrefix : "",
attrNodeName: "attr", //default is 'false'
textNodeName : "",
ignoreAttributes : false,
ignoreNameSpace : false,
allowBooleanAttributes : false,
parseNodeValue : true,
parseAttributeValue : true,
trimValues: true,
decodeHTMLchar: false,
cdataTagName: "__cdata", //default is 'false'
cdataPositionChar: "\c",
};
const myXml = '';
const tObj = xmlParser.getTraversalObj(myXml, XML_PARSER_OPTIONS);
tObj.child.toptag[0].child.forEach((nodeObj) => {
console.log(nodeObj.tagname);
});

Code

const XML_PARSER_OPTIONS = {
    attributeNamePrefix : "",
    attrNodeName: "attr", //default is 'false'
    textNodeName : "",
    ignoreAttributes : false,
    ignoreNameSpace : false,
    allowBooleanAttributes : false,
    parseNodeValue : true,
    parseAttributeValue : true,
    trimValues: true,
    decodeHTMLchar: false,
    cdataTagName: "__cdata", //default is 'false'
    cdataPositionChar: "\\c",
};
const myXml = '<toptag><mychild id="1" /><mydog id="2" /><mycat id="3" /><mydog id="4" /></toptag>';
const tObj = xmlParser.getTraversalObj(myXml, XML_PARSER_OPTIONS);
tObj.child.toptag[0].child.forEach((nodeObj) => {
      console.log(nodeObj.tagname);
 });

Output data

Please include output data here
tObj.child.toptag[0].child.forEach is not a function

expected data

Please include expected output data here
mychild
mydog
mycat
mydog

Leaves out Key/Value pair when value contains single quotes

Not sure if this is intended or not, but take the following
<Event time="00:05:00" customAttr="5" ID="568" Name="'Some Name' some more alpha numeric string ">

When this is parsed the Name attribute is skipped.

How can I either write a custom validation on key/values, or set an option to allow this? Or is this a bug?

I will add, it parses correctly in xml2js

parse fail to get attribute

Hi,

when I try to parse string like <tagname prop1="prop1" />the parser fail to get the property

fastXmlParser.parse('<tagname prop1="prop1" />') return empty object
fastXmlParser.parse('<tagname prop1="prop1"></tagname>') return expected object

There is any option I'm missing?
I currently use those options:

parserOptions = {
        attrPrefix : "__",
        textNodeName : "#text",
        ignoreNonTextNodeAttr : false,
        ignoreTextNodeAttr : false,
        ignoreNameSpace : false
    }

Doesn't support attributes by default.

Great lib. Attribute parsing is off by default. I needed to add the correct options object to make it work.

var options = {
    attrPrefix : "@_",
    textNodeName : "#text",
    ignoreNonTextNodeAttr : false,
    ignoreTextNodeAttr : false,
    ignoreNameSpace : false,
    textNodeConversion : true
};

obtain xml text

How might I access the value '71' in this example? <score><c1>71<message>23</message></c1></score>

fast-xml-parser:
score: {
c1:
{ message: 23 }}

xml2js:
score: {
c1:
{ _: 71,
message: 23 } }

Thank you.

fast-xml-parser in an Angular CLI environment

Hello,
I need help.

  • I created an Angular CLI (1.6.5) project and after that I install fast-xml-parser (npm install fast-xml-parser --save (2.9.3) and run the app with ng serve. Until here everything is OK.

  • Now I try to use it in the way you described

In a default component I try to add the require
`
import { Injectable } from '@angular/core';
var fastXmlParser = require('fast-xml-parser');

`

ng serve detect the change and shows the error
`webpack: Compiled successfully.
webpack: Compiling...
90% chunk assets processingERROR in src/app/i-hub/imp-exp.service.ts(4,21): error TS2304: Cannot find name 'require'.
Date: 2018-01-30T10:22:19.516Z • Hash: d91f217da47d8c3a4021 • Time: 2927ms
3 unchanged chunks
chunk {main} main.bundle.js (main) 59.3 kB [initial] [rendered]
chunk {vendor} vendor.bundle.js (vendor) 14.4 MB [initial] [rendered]

webpack: Compiled successfully.`

What should I do with the unknown require error, how could I solve this

Issue with XML containing subdeclaration

  • Are you running the latest version?
  • Have you include sample input?
  • Have you include actual output?
  • Have you include expected output?
  • Have you checked if you are using correct configuration?
  • Did you try online tool?
  • Did you bookmarked the repository for further updates? ;)

Input data

require('fast-xml-parser').validate(`<?xml version="1.0"?><?mso-contentType?><h1></h1>`)

Output data

{ err:
   { code: 'InvalidXml',
     msg: 'XML declaration allowed only at the start of the document.' } }

expected data

true

Parse <![CDATA[0]]> to ""

Hello.
I get the error that this xml tag

is parsed to section="" Supposed to be section=0 ![image 11](https://user-images.githubusercontent.com/9316087/28584688-46af8b4e-7176-11e7-9e83-8e90ac9230db.png) ![image 12](https://user-images.githubusercontent.com/9316087/28584689-46b07022-7176-11e7-99f4-bda11c63f634.png)

Detail on Array mode

@Delagen , I'm rewriting the XML parser to handle large files and for other useful features. Hence I was revisiting the test cases. As you did the changes to parse attributes as array in #23 , I have a query to clear the expectations;

In the test "should parse nodes as arrays" in file xmlParser_spec.js, somewhere attribute is parsed as object and somewhere as array.


"any_name": [{
        "@attr": ["https://example.com/somepath"],
        "person": [{
   :
          "age": [34],
          "married": [{
              "@firstTime": "Yes",
              "#_text": "Yes"
          }],

Can you please clear me the expectation so I'll implement the same in new code?

In my understanding / expectations

<types>textdetail
    <type>val</type>
    <type attr="value">val</type>
    <type attr="value">val
        <nestedtag>val</nestedtag>
    </type>
    <type attr="value"></type>
    <type>val</type>
    <config>someconfig</config>
</types>
"types": [ {
            "#text": [ "textdetail" ],
            "type": [
                "val",
                { "@attr": ["value"], "#text": ["val"] },
                { "@attr": ["value"], "#text": ["val"] , "nestedtag" : ["val"]},
                { "@attr": ["value"]},
                "val"
            ],
            "config": [ "someconfig" ]
    }]

Improve validator performance

Hi,

First the Parser is incredible fast - good job!
For 5.7MB XML (multiple files, parse parallel) it needs ~150ms (xml2js needs ~2200ms).
But with validation it needs ~14644ms (!sic).

You can reproduce this even on the "try me" page when you copy/paste more person-elements in the xml. While "parse to Json" stays fast, the validation time seems to grow exponentially.

It would be great if you can improve the performance.

Decode HTML entities in text values

Checklist

  • Are you running the latest version?
  • Include sample input XML
  • Include actual output
  • Include expected output
  • Did you try online tool?
  • Did you star the repository for further updates? ;)

I include PR soon

NPE on validate()

validate('<submission xmlns="http://opendatakit.org/submissions" xmlns:orx="http://openrosa.org/xforms"><data><data id="build_Untitled-Form_1424401835" instanceID="uuid:70ab6d82-110a-4ba6-86ac-071d698fd3a3" submissionDate="2015-02-20T16:07:51.145Z" isComplete="true" markedAsCompleteDate="2015-02-20T16:07:51.145Z"><orx:meta><orx:instanceID>uuid:74ab6d82-110a-4ba6-86ac-071d698fd3a3</orx:instanceID></orx:meta><name>Trevor</name><age>31</age><birthday>2014-07-01</birthday><location/><photo>1424448426991.jpg</photo><favorite_color>blue</favorite_color></data></data>');

On version 2.7.4, this fails for me on validator.js:76 with an NPE on the reference to index 0.

Object.assign is not supported in IE

Checklist

Please fill below checklist

  • Are you running the latest version?
  • Have you include sample input? NA
  • Have you include actual output? NA
  • Have you include expected output? NA
  • Have you checked if you are using correct configuration?
  • Did you try online tool?
  • Did you bookmarked the repository for further updates? ;)

Output data

IE error

expected data

It should work fine on IE

Note : Originally reported by @Delagen in a comment on a commit.

Validator fails for valid SVG file

Tha validator returns false for this SVG file:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Generator: Adobe Illustrator 13.0.2, SVG Export Plug-In . SVG Version: 6.00 Build 14948)  -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg version="1.0" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="64px" height="64px" viewBox="5.5 -3.5 64 64" enable-background="new 5.5 -3.5 64 64" xml:space="preserve">
<g>
	<circle fill="#FFFFFF" cx="37.637" cy="28.806" r="28.276"/>
	<g>
		<path d="M37.443-3.5c8.988,0,16.57,3.085,22.742,9.257C66.393,11.967,69.5,19.548,69.5,28.5c0,8.991-3.049,16.476-9.145,22.456    C53.879,57.319,46.242,60.5,37.443,60.5c-8.649,0-16.153-3.144-22.514-9.43C8.644,44.784,5.5,37.262,5.5,28.5    c0-8.761,3.144-16.342,9.429-22.742C21.101-0.415,28.604-3.5,37.443-3.5z M37.557,2.272c-7.276,0-13.428,2.553-18.457,7.657    c-5.22,5.334-7.829,11.525-7.829,18.572c0,7.086,2.59,13.22,7.77,18.398c5.181,5.182,11.352,7.771,18.514,7.771    c7.123,0,13.334-2.607,18.629-7.828c5.029-4.838,7.543-10.952,7.543-18.343c0-7.276-2.553-13.465-7.656-18.571    C50.967,4.824,44.795,2.272,37.557,2.272z M46.129,20.557v13.085h-3.656v15.542h-9.944V33.643h-3.656V20.557    c0-0.572,0.2-1.057,0.599-1.457c0.401-0.399,0.887-0.6,1.457-0.6h13.144c0.533,0,1.01,0.2,1.428,0.6    C45.918,19.5,46.129,19.986,46.129,20.557z M33.042,12.329c0-3.008,1.485-4.514,4.458-4.514s4.457,1.504,4.457,4.514    c0,2.971-1.486,4.457-4.457,4.457S33.042,15.3,33.042,12.329z"/>
	</g>
</g>
</svg>

The source of the file is http://mirrors.creativecommons.org/presskit/icons/by.svg and it’s valid according to W3C Markup Validation Service.

I pushed the SVG and a test case here: gxa@aeec187

Error: Cannot find module 'fast-xml-parser'

When installing fast-xml-parser as dependency and using in a project, it gives error Error: Cannot find module 'fast-xml-parser'. This propblem occurs only for latest version i.e. 3.3.1. Everything is normal and running fine till version 3.3.0

Input data

NA

Code

NA

Output data

Error: Cannot find module 'fast-xml-parser'

expected data

parser should be included and working fine.

parse content in cdata has error

look this example:

<xml>
<a>text</a>
<b>
    text
</b>
<c>
    <![CDATA[text]]>
</c>
<d><![CDATA[text]]></d>
</xml>

the parse result was:

{
    "xml": {
        "a": "text",
        "b": "     text\n",
        "c": null,
        "d": "text"
    }
}

as above shown, when cdata tag was start in newline, the parse result was null.

i wonder if it was a bug or my wrong usage ? i just use the default options.

Parse attr failed when the attr text has "="

const xml = <issue entity="Mjg2MzY2OTkyNA==" state="partial" version="1"></issue>
fastXmlParser.parse(xml, {
attrPrefix : "@",
attrNodeName: false,
textNodeName : "#text",
ignoreNonTextNodeAttr : false,
ignoreTextNodeAttr : false,
ignoreNameSpace : false,
ignoreRootElement : false,
textNodeConversion : true,
textAttrConversion : false,
arrayMode : false
});

parse attr fails when attribute contains newline

<element id="7" data="foo
bar" bug="true"/>

The data attribute does not show up. I assume this will be fixed with parsing change mentioned in #30. The real life use case is an SVG file with embedded bitmap image that has an attribute like:

<image
  xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAAExCA
...
Nhfphem9d9wxe/e73/XQdddd/4Vbb71Vn1neDN+LGvh/NgDkIaZnFBUAAAAASUVORK5CYII=
"/>

Wrong output

Hi,
Thank you for your library.
I have a problem with this XML that is transformed into the following JSON me this and the structure is really not the same between the two.

<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">
    <s:Header>
        <a:Action s:mustUnderstand="1">http://www.b-i.com/ns/LoyaltyWebservice/IParticipationService/GetUserProfileResponse</a:Action>
    </s:Header>
    <s:Body>
        <GetUserProfileResponse xmlns="http://www.b-i.com/ns/LoyaltyWebservice">
            <GetUserProfileResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
                <Data i:type="ConsumerData">
                    <UserProfile>
                        <Age>28</Age>
                        <Birthday>1988-07-13T00:00:00</Birthday><BrandComPrefID i:nil="true"/><BrandComPrefName i:nil="true"/>
                        <City>Annecy</City>
                        <ConsumerID>5081695</ConsumerID>
                        <ConsumerNumber>5081695</ConsumerNumber><DeeplinkToken i:nil="true"/>
                        <DeliveryCity>Annecy</DeliveryCity><DeliveryPhone i:nil="true"/>
                        <DeliveryStreetAddress>avenue de geneve</DeliveryStreetAddress><DeliveryStreetNumber i:nil="true"/>
                        <DeliveryZipCode>74000</DeliveryZipCode>
                        <Email>[email protected]</Email>
                        <FestivalId>0</FestivalId>
                        <FirstName>Lory</FirstName>
                        <Gender>Male</Gender><HomePhone i:nil="true"/>
                        <IsLAMP>false</IsLAMP>
                        <IsMainBrandPM>false</IsMainBrandPM>
                        <IsOccasionalBrandPM>false</IsOccasionalBrandPM>
                        <LastName>Bineau</LastName>
                        <LoginID>1250221</LoginID><LoginNumber i:nil="true"/>
                        <MainBrandID>8907</MainBrandID><MainBrandName i:nil="true"/>
                        <MainBrandOpinion>0</MainBrandOpinion><MobilePhone i:nil="true"/><OccasionalBrandID i:nil="true"/><OccasionalBrandName i:nil="true"/><POBoxCity i:nil="true"/><POBoxNumber i:nil="true"/><POBoxZIPCode i:nil="true"/>
                        <PersonId>5081695</PersonId>
                        <PreferredLanguage>2</PreferredLanguage>
                        <Properties>
                            <Properties>
                                <ExtendedProperty>
                                    <Key>CanClaimIncentive</Key>
                                    <Value>False</Value>
                                </ExtendedProperty>
                                <ExtendedProperty>
                                    <Key>Competitor</Key>
                                    <Value>False</Value>
                                </ExtendedProperty>
                                <ExtendedProperty>
                                    <Key>FullFlavor</Key>
                                    <Value>True</Value>
                                </ExtendedProperty>
                                <ExtendedProperty>
                                    <Key>Segment</Key>
                                    <Value>0</Value>
                                </ExtendedProperty>
                                <ExtendedProperty>
                                    <Key>Above8</Key>
                                    <Value>True</Value>
                                </ExtendedProperty>
                                <ExtendedProperty>
                                    <Key>GoldSecondary</Key>
                                    <Value>False</Value>
                                </ExtendedProperty>
                                <ExtendedProperty>
                                    <Key>SpokenLanguage</Key>
                                    <Value>FR</Value>
                                </ExtendedProperty>
                                <ExtendedProperty>
                                    <Key>ShowGame</Key>
                                    <Value>False</Value>
                                </ExtendedProperty>
                                <ExtendedProperty>
                                    <Key>PointBalance</Key>
                                    <Value>50</Value>
                                </ExtendedProperty>
                                <ExtendedProperty>
                                    <Key>CarTickets</Key>
                                    <Value>0</Value>
                                </ExtendedProperty>
                                <ExtendedProperty>
                                    <Key>Influencer</Key>
                                    <Value>False</Value>
                                </ExtendedProperty>
                            </Properties>
                        </Properties>
                        <StreetAddress>avenue de geneve</StreetAddress>
                        <StreetNumber>43b</StreetNumber>
                        <WebSurveyCompleted>false</WebSurveyCompleted>
                        <ZipCode>74000</ZipCode>
                    </UserProfile>
                </Data>
                <Details>Lory Bineau</Details>
                <Result>200</Result>
            </GetUserProfileResult>
        </GetUserProfileResponse>
    </s:Body>
</s:Envelope>

=>

{
    "s:Envelope": {
        "s:Header": {
            "a:Action": "http://www.b-i.com/ns/LoyaltyWebservice/IParticipationService/GetUserProfileResponse"
        },
        "s:Body": {
            "GetUserProfileResponse": {
                "GetUserProfileResult": {
                    "Data": {
                        "UserProfile": {
                            "Age": 28,
                            "Birthday": "1988-07-13T00:00:00",
                            "BrandComPrefID": {
                                "BrandComPrefName": {
                                    "City": "Annecy",
                                    "ConsumerID": 5081695,
                                    "ConsumerNumber": 5081695,
                                    "DeeplinkToken": {
                                        "DeliveryCity": "Annecy",
                                        "DeliveryPhone": {
                                            "DeliveryStreetAddress": "avenue de geneve",
                                            "DeliveryStreetNumber": {
                                                "DeliveryZipCode": 74000,
                                                "Email": "[email protected]",
                                                "FestivalId": {},
                                                "FirstName": "Lory",
                                                "Gender": "Male",
                                                "HomePhone": {
                                                    "IsLAMP": "false",
                                                    "IsMainBrandPM": "false",
                                                    "IsOccasionalBrandPM": "false",
                                                    "LastName": "Bineau",
                                                    "LoginID": 1250221,
                                                    "LoginNumber": {
                                                        "MainBrandID": 8907,
                                                        "MainBrandName": {
                                                            "MainBrandOpinion": {},
                                                            "MobilePhone": {
                                                                "OccasionalBrandID": {
                                                                    "OccasionalBrandName": {
                                                                        "POBoxCity": {
                                                                            "POBoxNumber": {
                                                                                "POBoxZIPCode": {
                                                                                    "PersonId": 5081695,
                                                                                    "PreferredLanguage": 2,
                                                                                    "Properties": {
                                                                                        "Properties": {
                                                                                            "ExtendedProperty": [{
                                                                                                "Key": "CanClaimIncentive",
                                                                                                "Value": "False"
                                                                                            }, {
                                                                                                "Key": "Competitor",
                                                                                                "Value": "False"
                                                                                            }, {
                                                                                                "Key": "FullFlavor",
                                                                                                "Value": "True"
                                                                                            }, {
                                                                                                "Key": "Segment",
                                                                                                "Value": {}
                                                                                            }, {
                                                                                                "Key": "Above8",
                                                                                                "Value": "True"
                                                                                            }, {
                                                                                                "Key": "GoldSecondary",
                                                                                                "Value": "False"
                                                                                            }, {
                                                                                                "Key": "SpokenLanguage",
                                                                                                "Value": "FR"
                                                                                            }, {
                                                                                                "Key": "ShowGame",
                                                                                                "Value": "False"
                                                                                            }, {
                                                                                                "Key": "PointBalance",
                                                                                                "Value": 50
                                                                                            }, {
                                                                                                "Key": "CarTickets",
                                                                                                "Value": {}
                                                                                            }, {
                                                                                                "Key": "Influencer",
                                                                                                "Value": "False"
                                                                                            }]
                                                                                        }
                                                                                    },
                                                                                    "StreetAddress": "avenue de geneve",
                                                                                    "StreetNumber": "43b",
                                                                                    "WebSurveyCompleted": "false",
                                                                                    "ZipCode": 74000
                                                                                }
                                                                            },
                                                                            "Details": "Lory Bineau",
                                                                            "Result": 200
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

CDATA parsing error with regular expression as content

Hello,

I am facing issue while parsing CDATA containing regular expressions as a value. Normal CDATA is parsing correctly but while using regular expressions as a value it returns blank string.
here is a sample XML for it

<?xml version="1.0" encoding="UTF-8"?><sample><![CDATA[test]]></sample><firstchar><![CDATA[^[ ].*$]]></firstchar>

could you please help to sort it out?

Thanks

no validate function

Hi,

I installed fast-xml-parser using npm install fast-xml-parser and there is no validate function in the object, only convertToJson , getTraversalObj and parse function.

I'm don't need it but just to warn you.

Self-closing tag is a non-text node whereas empty tag is a text node

<tag id="foo"/> and <tag id="foo"></tag> are treated differently. To parse the attributes in the first case you need to specify ignoreNonTextAttr: false and for the second case ignoreTextAttr:false. Also, the second tag will have a #text field and the first one won’t. I think this behaviour doesn’t match the XML spec, as the two should be equivalent:

Empty-element tags may be used for any element which has no content, whether or not it is declared using the keyword EMPTY. For interoperability, the empty-element tag SHOULD be used, and SHOULD only be used, for elements which are declared EMPTY.

Examples of empty elements:

<IMG align="left"
src="http://www.w3.org/Icons/WWW/w3c_home" />
<br></br>
<br/>

parse option ArrayMode not working

Checklist

Please fill below checklist

  • Are you running the latest version? 3.3.6
  • Have you include sample input?
  • Have you include actual output?
  • Have you include expected output?
  • Have you checked if you are using correct configuration?
  • Did you try online tool?
  • Did you bookmarked the repository for further updates? ;)

Input data

<x><y><z>z1</z><z>z2</z></y><w>w1</w></x>

Code

import * as FXP from "fast-xml-parser";
import { parseString } from "xml2js";

const xml = "<x><y><z>z1</z><z>z2</z></y><w>w1</w></x>";
parseString(xml, { explicitArray: false }, (err, res) => console.log("xml2js      ", JSON.stringify(res)));
parseString(xml, { explicitArray: true }, (err, res) => console.log("xml2js array", JSON.stringify(res)));
console.log("FXP         ", JSON.stringify(FXP.parse(xml)));
console.log("FXP array   ", JSON.stringify(FXP.parse(xml, { arrayMode: true })));

Output data

xml2js       {"x":{"y":{"z":["z1","z2"]},"w":"w1"}}
xml2js array {"x":{"y":[{"z":["z1","z2"]}],"w":["w1"]}}
FXP          {"x":{"y":{"z":["z1","z2"]},"w":"w1"}}
FXP array    {"x":{"y":{"z":["z1","z2"]},"w":"w1"}}

expected data

xml2js       {"x":{"y":{"z":["z1","z2"]},"w":"w1"}}
xml2js array {"x":{"y":[{"z":["z1","z2"]}],"w":["w1"]}}
FXP          {"x":{"y":{"z":["z1","z2"]},"w":"w1"}}
FXP array    {"x":{"y":[{"z":["z1","z2"]}],"w":["w1"]}}

Unable to find v3.x

I'm using 1.x version of parser. I checked the cdn and didn't find any references to v3. How do I get the version as single file.

Valid XML with open quotes is marked as invalid

Checklist

  • Are you running the latest version? : 3.2.3
  • Have you include sample input?
  • Have you include actual output?
  • Have you include expected output?
  • Have you checked if you are using correct configuration?
  • Did you try online tool?
  • Did you bookmarked the repository for further updates? ;)

Input data

When I run the following code :

require('fast-xml-parser').validate(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><h1 a="fo'a"></h1>`)

I get :

{ err:
   { code: 'InvalidAttr',
     msg: 'Attributes for h1 have open quote' } }

Online, with the same input data, the error doesn't appear, but I think you might be using parse instead of validate (which also works locally)

I would expect the result to be a validationsuccess (return true)

It is allowed to have the single quote character if using double quotes as the delimiters (see https://stackoverflow.com/a/866894/1993501)

Missing attribute details while converting from xml to json

The script works well, but the attribute details is not there in the converted JSON. I've attached the dummy.xml file and there is no detail in the output for attribute and its value while converting this specific file in json.

I'm unable to upload the xml file therefore here is a snippet:

<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <price>44.95</price>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <price>5.95</price>
   </book>
   <book id="bk103">
      <author>Corets, Eva</author>
      <title>Maeve Ascendant</title>
      <price>5.95</price>
   </book>
</catalog>

The id="#nodeID" is missing in the conversion, it just make array for each node of .

Note: There should be converter from json to xml, so it can work back and fourth.

Can't get CDATA section content

Hi,

It seems that CDATA section are ignored when parsing XML, and produce an invalid "Invalid comment" exception when validating.

For exemple, this XML:

<?xml version="1.0"?>
<any_name>
    <person>
        <phone>+122233344550</phone>
        <name><![CDATA[Jack]]></name>
        <phone>+122233344551</phone>
    </person>
</any_name>

produces:

{
    "any_name": {
        "person": {
            "phone": [
                122233344550,
                122233344551
            ],
            "name": ""
        }
    }
}

Is there a way to make fast-xml-parser put CDATA content as the string value of the property (name: "Jack" in the exemple)?

Text nodes are compressed together, is that normal ?

Checklist

Please fill below checklist

  • Are you running the latest version?
  • Have you include sample input?
  • Have you include actual output?
  • Have you include expected output?
  • Have you checked if you are using correct configuration?
  • Did you try online tool?
  • Did you bookmarked the repository for further updates? ;)

Input data

<p>text on the left <b>text in the middle</b> text on the right</p>

Code

const xml = '<p>text on the left <b>text in the middle</b> text on the right</p>';

let obj = fastXmlParser.parse(xml, {
    attributeNamePrefix : '@_',
    ignoreAttributes : false,
    allowBooleanAttributes : true,
    cdataTagName: "__cdata",
    cdataPositionChar: "\\c",
});

console.log(obj);

Output data

{ p:
   { b: 'text in the middle',
     '#text': 'text on the lefttext on the right' }
}

expected data

Not sure how...
Maybe #text could be an array representing the original layout and also referencing tag...

{ p:
   { b: 'text in the middle',
     '#text': ['text on the left','<b>','text on the right'] }
}

This one may be too much..

[
  { p: [
    {'#text': 'text on the left'},
    { b: 'text in the middle'},
    {'#text': 'text on the right'}
  ]}
]

I'm using it to parse HTML, validate and render back in html a portion of the tree. Maybe I'm not using the right tool ?

Since 2.9.*, that XML became invalid

Since the 2.9.0 release, the below xml become invalid when using xmlParser.validate(xml).

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE daily_western_horo_fr>
<daily_western_horo_fr>
   <date valeur="2018-01-24">
      <signe valeur="vierge">
         <amour>La vie de couple s'accompagne de tâches pas toujours très agréables à réaliser. Aujourd'hui, cela ne vous gênera pas. Qu'il s'agisse de ménage, de cuisine ou de gestion du foyer, vous trouverez cela normal et serez heureux de le faire, car vous vous sentez responsable de votre petit monde. Vous vous montrerez adorable quoi qu'il arrive.</amour>
         <argent>Ah ! Les imprévus ! Que vous n'aimez pas ça ! Et pourtant, c'est ce qui risque d'arriver aujourd'hui, en raison d'influx dissonants Lune/Uranus dans le secteur concerné. Rassurez-vous, votre gestion impeccable devrait vous permettre d'assurer sans problème.</argent>
         <sante>Vous canaliserez à merveille votre énergie. Votre esprit est pratique et vous possédez un excellent sens de l'organisation. Tout roule !</sante>
         <travail>Toujours soucieux de rendre un travail impeccable, vous serez en mode perfection. Comme la perfection n'existe pas, vous essaierez au moins de vous en rapprocher le plus possible. Vous perdrez du temps pour des détails que personne ne remarquera...</travail>
         <famille_foyer>Vous serez heureux de partager de petits plaisirs simples et spontanés avec les enfants comme avec les plus grands. L'ambiance se fera très complice.</famille_foyer>
         <vie_sociale>Vos amis seront tentés de faire appel à vos capacités de jugement. Ils savent que vous ne laissez rien au hasard et que lorsque vous affirmez quelque chose, ils peuvent vous faire confiance.</vie_sociale>
         <citation>« L'absence est le plus grand des maux. » La Fontaine</citation>
         <nombre_chance>23</nombre_chance>
         <clin_doeil>Vous serez très ouvert à de nouvelles sensations, mais en aurez-vous l'opportunité ? Si vous n'êtes pas très clair sur vos intentions, vous passerez à côté d'une occasion.</clin_doeil>
      </signe>
   </date>
</daily_western_horo_fr>

It seems to work on the online tool.
Maybe I use the validate in a wrong way?

Checklist

  • Are you running the latest version?
  • Include sample input XML
  • Include actual output
  • Include expected output
  • Did you try online tool?
  • Did you star the repository for further updates? ;)

CDATA Parsing Issue

Hi, Not parsing the CDATA correctly. It is able to parse the CDATA when the elements are formatted like this.

if the xml formatted like this - It is failing to get the data.

Instead of depending on the substring logic it should read the whole text between the tags. Please let me know if you have time to fix this issue otherwise will try to look for another solution.

Creating tag/release on GitHub each time you release a new version on NPM

My project got some validation problem on some XML using 2.9.* version of your library.
2.8.* is working great.

Since you didn't create tag or release on GitHub I can't compare what changed on your side to understand why parsing is failing.

Could you create tag / release on GitHub each time you release a new version on NPM? At least for future release because I guess it'll be hard for previous release.

Thanks.

Feature Request: TypeScript type definitions

Hi there,
it would be great if fast-xml-parser had typescript support.

Would you be willing to include types directly here? The advantage would be that users wouldn't need manually install types.

Another option would be externally, e.g. similar like xml2js: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/xml2js.
Users would then need to install the types package manually as described here: https://www.npmjs.com/package/@types/xml2js
Another disadvantage is that the types might become out of sync with the code more easily.

What way would you prefer, if any?

Why carriage return removed from values?

Checklist

  • Are you running the latest version?
  • Include sample input XML
  • Include actual output
  • Include expected output
  • Did you try online tool?
  • Did you star the repository for further updates? ;)

I think

xmlData = xmlData.replace(/\r?\n/g, " ");//make it single line

should be removed
but

function buildAttributesMap(attrStr,options){
    attrStr = attrStr.replace(/\r?\n/g, " ");

But with this does not removed comments

xmlData = xmlData.replace(/<!--[\s\S]*?-->/g, "");//Remove  comments

resolves this

IE ParseInt Error

IE not Support Number.parseInt()

Chrome Support

Number.parseInt -> parseInt()

change plz... have a nice day~

screenshot_2

screenshot_1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.