convert javascript to xml using python

In this article we are going to convert a javascript code to xml data using python. This can be achieved with the help of a python library called js2xml. This makes it easy to extract data embedded in JavaScript code using XPath in a way more robust than just using regular expressions.

This package can be easily installed from pip or cloning the repo and installing it. The link to the library’s github page is here.

Installation

Install the package by running the following command on your terminal.

pip install js2xml

Example

Let us see a simple example to convert a javascript code to xml format. Consider a javascript string like this. The function to find the factorial of a number is used here.

The parse() method in the js2xml library takes the string as input and returns the xml code of the javascript function.

The entire script can be written easily written like this.

This code will give us an output like this. This is nothing but the xml data of the javascript function.

<program>
  <funcdecl name="factorial">
    <parameters>
      <identifier name="n"/>
    </parameters>
    <body>
      <if>
        <predicate>
          <binaryoperation operation="===">
            <left>
              <identifier name="n"/>
            </left>
            <right>
              <number value="0"/>
            </right>
          </binaryoperation>
        </predicate>
        <then>
          <block>
            <return>
              <number value="1"/>
            </return>
          </block>
        </then>
      </if>
      <return>
        <binaryoperation operation="*">
          <left>
            <identifier name="n"/>
          </left>
          <right>
            <functioncall>
              <function>
                <identifier name="factorial"/>
              </function>
              <arguments>
                <binaryoperation operation="-">
                  <left>
                    <identifier name="n"/>
                  </left>
                  <right>
                    <number value="1"/>
                  </right>
                </binaryoperation>
              </arguments>
            </functioncall>
          </right>
        </binaryoperation>
      </return>
    </body>
  </funcdecl>
</program>

We can also find the function name using path like this.

That is it. Feel free to explore with the other methods available in the package.

Happy coding!