Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What fast-xml-parser options preserve namespace and attributes when parsing and generating XML documents?

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?

like image 570
Derek Mahar Avatar asked Oct 17 '22 10:10

Derek Mahar


1 Answers

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>
like image 56
Amit Kumar Gupta Avatar answered Oct 21 '22 00:10

Amit Kumar Gupta