scrapinghub / js2xml

Convert Javascript code to an XML document
MIT License
186 stars 23 forks source link
hacktoberfest javascript python xml

js2xml

Tests codecov

Convert Javascript code to an XML document.

This makes it easy to extract data embedded in JavaScript code using XPath in a way more robust than just using regular expressions.

Install:

You can install js2xml via PyPI:

pip install js2xml

Example:

>>> import js2xml
>>>
>>> jscode = """function factorial(n) {
...     if (n === 0) {
...         return 1;
...     }
...     return n * factorial(n - 1);
... }"""
>>> parsed = js2xml.parse(jscode)
>>>
>>> parsed.xpath("//funcdecl/@name")  # extracts function name
['factorial']
>>>
>>> print(js2xml.pretty_print(parsed))  # pretty-print generated XML
<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>

>>>

Changelog

v0.5.0 (2022-03-14)

v0.4.0 (2020-06-04)

v0.3.1 (2017-08-03)

v0.3.0 (2017-08-03)

v0.2.3 (2017-05-30)

v0.2.2 (2016-12-01)

v0.2.1 (2016-06-10)

v0.2.0 (2016-06-10)

v0.1.2 (2015-05-11)

v0.1.1 (2014-08-13)

v0.1 (2014-08-12)

Initial release