• Ask a Question
  • Create a Poll
    Ask a Question
    More answer You can create 5 answer(s).
      Ask a Poll

      TypeScript adding node to exsisting XML

      I have a XML that structure looks like this

      <?xml version="1.0" encoding="UTF-8"?> <parent>    <kid>    </kid> </parent> 

      I wanna simply add few nodes inside parent node that it will become something like this

      <?xml version="1.0" encoding="UTF-8"?> <parent>    <kid>    </kid>     <data>         <data_kid_1>{ JSON OBJECT }</data_kid_1>         <data_kid_2>false</data_kid_2>     </data> </parent> 

      I have tried to use XmlJs.xml2js() convert my XML to JavaScript and then add it in that way:

              let jScriptXml['parent']['data'] = {             'data_kid_1': { JSON OBJECT } ,             'data_kid_2': false         }; 

      followed by converting it back to XML using XmlJs.js2xml() but conversion do not convert signs like & or < to entity references and that cause errors in my app

      Anyone have an idea how to add that nodes without breaking XML?

      2 Answers

      Not the most beautiful code in the world, but it does deliver, I think:

      kids = `<?xml version="1.0" encoding="UTF-8"?> <parent>    <kid>    </kid> </parent>`  xpath = require('xpath')  , dom = require('xmldom').DOMParser;  XMLSerializer = require('xmldom').XMLSerializer; serializer = new XMLSerializer(); family = new dom().parseFromString(kids);  destination = xpath.select('//kid', family, true); data = family.createElement("data"); data.appendChild(family.createTextNode("\r\n\t    "));//I added a few new lines, etc., just for presentation, but they're not strictly necessary kid1 = family.createElement("data_kid_1"); kid1.appendChild(family.createTextNode("{ JSON OBJECT }")); kid2 = family.createElement("data_kid_2"); kid2.appendChild(family.createTextNode("false")); data.appendChild(kid1); data.appendChild(family.createTextNode("\r\n\t    ")); data.appendChild(kid2); data.appendChild(family.createTextNode("\r\n\t"));  destination.parentNode.insertBefore(data, destination.nextSibling);//drop .nextSibling to actually insert before destination.parentNode.insertBefore(family.createTextNode("\r\n\t"), destination.nextSibling); console.info(serializer.serializeToString(family)) 


      <?xml version="1.0" encoding="UTF-8"?> <parent>    <kid>    </kid>     <data>         <data_kid_1>{ JSON OBJECT }</data_kid_1>         <data_kid_2>false</data_kid_2>     </data> </parent> 
      Answered by Jonasclarissadorothy on July 17, 2020..

      Or maybe there is a way to remove entity reference using XmlJs.js2xml(js_xml_data, options); with proper options setup. I tried to use sanitize: true but it does not work. Anyone has experience with using XmlJs?

      Answered by Fredtamikamarcella on July 17, 2020..