What fast-xml-parser options should I use in order to parse an input XML document to JSON and then write the identical XML document, preserving all namespace and attribute names and values?
Since you want to preseve the attributes and namespace then ignoreAttributes
and ignoreNameSpace
should be set to false. Attribute prefix should be the same while parsing from XML to JS object and back to XML. Here is the complete example;
const xmlInput = `<any_name a="abc">
<ns:person>
<name1>Jack 1</name1 >
<name2>35</name2>
</ns:person>
</any_name>`;
const options = {
attributeNamePrefix : "@_",
//attrNodeName: false,
//textNodeName : "#text",
ignoreAttributes : false,
ignoreNameSpace: false,
};
const jsonOptions = {
attributeNamePrefix : "@_",
//attrNodeName: false,
//textNodeName : "#text",
ignoreAttributes : false,
ignoreNameSpace: false,
//format: true,
//indentBy: " ",
//supressEmptyNode: false,
};
const json = x2jParser.parse(xmlInput, options);
const parserJson = new j2xParser(jsonOptions);
const xmlOutput = parserJson.parse(json, jsonOptions);
Input XML
<any_name a="abc">
<ns:person>
<name1>Jack 1</name1 >
<name2>35</name2>
</ns:person>
</any_name>
Output XML
<any_name a="abc">
<ns:person>
<name1>Jack 1</name1>
<name2>35</name2>
</ns:person>
</any_name>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With