[
  {
    "path": ".gitignore",
    "content": "*pyc\n__pycache__/*\n"
  },
  {
    "path": "LICENSE",
    "content": "Copyright (C) 2010-2013, Hay Kranen\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."
  },
  {
    "path": "README.md",
    "content": "XML2JSON\n========\n\n**This module is deprecated and will not be updated anymore (May 2019)**\n\n* To convert between text-based data formats (including XML and JSON) use my library [`dataknead`](http://github.com/hay/dataknead).\n* To work with XML in Python i recommend the excellent [`xmltodict`](https://github.com/martinblech/xmltodict).\n\n## Deprecated documentation\n\nPython script converts XML to JSON or the other way around\n\nUsage\n-----\nMake this executable\n\n    $ chmod +x xml2json\n\nThen invoke it from the command line like this\n\n    $ xml2json -t xml2json -o file.json file.xml\n\nOr the other way around\n\n    $ xml2json -t json2xml -o file.xml file.json\n\nWithout the `-o` parameter `xml2json` writes to stdout\n\n    $ xml2json -t json2xml file.json\n\nAdditional the options:\nStrip text (#text and #tail) in the json\n\n    $ xml2json -t xml2json -o file.json file.xml --strip_text\n\nStrip namespace in the json\n\n    $ xml2json -t xml2json -o file.json file.xml --strip_namespace\n\nIn code\n\n    from xml2json import json2xml\n    d = {'r': {'@p': 'p1', '#text': 't1', 'c': 't2'}}\n    print(json2xml(d))\n    > b'<r p=\"p1\">t1<c>t2</c></r>'\n    \nInstallation\n------------\nEither clone this repo or use `pip` like this:\n\n    pip install https://github.com/hay/xml2json/zipball/master\n\nLicense\n-------\nxml2json is released under the terms of the [MIT license](http://opensource.org/licenses/MIT).\n\nContributors\n------------\nThis script was originally written by R.White, Rewritten to a command line utility by [Hay Kranen](http://www.haykranen.nl) with contributions from George Hamilton (gmh04) and Dan Brown (jdanbrown)\n\nLinks\n------\n* [Github](http://github.com/hay/xml2json)\n\nHow it works\n------------\nxml2json relies on ElementTree for the XML parsing.  This is based on\npesterfish.py but uses a different XML->JSON mapping.\nThe XML -> JSON mapping is described [here](http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html)\n\n<pre>\nXML                              JSON\n&lt;e/&gt;                             \"e\": null\n&lt;e&gt;text&lt;/e&gt;                      \"e\": \"text\"\n&lt;e name=\"value\" /&gt;               \"e\": { \"@name\": \"value\" }\n&lt;e name=\"value\"&gt;text&lt;/e&gt;         \"e\": { \"@name\": \"value\", \"#text\": \"text\" }\n&lt;e&gt; &lt;a&gt;text&lt;/a &gt;&lt;b&gt;text&lt;/b&gt; &lt;/e&gt; \"e\": { \"a\": \"text\", \"b\": \"text\" }\n&lt;e&gt; &lt;a&gt;text&lt;/a&gt; &lt;a&gt;text&lt;/a&gt; &lt;/e&gt; \"e\": { \"a\": [\"text\", \"text\"] }\n&lt;e&gt; text &lt;a&gt;text&lt;/a&gt; &lt;/e&gt;        \"e\": { \"#text\": \"text\", \"a\": \"text\" }\n</pre>\n\nThis is very similar to the mapping used for [Yahoo Web Services](http://developer.yahoo.com/common/json.html#xml)\n\nThis is a mess in that it is so unpredictable -- it requires lots of testing (e.g. to see if values are lists or strings or dictionaries).  For use in Python this could be vastly cleaner.  Think about whether the internal form can be more self-consistent while maintaining good external characteristics for the JSON.\n\nLook at the Yahoo version closely to see how it works.  Maybe can adopt that completely if it makes more sense...\n\nR. White, 2006 November 6\n"
  },
  {
    "path": "setup.py",
    "content": "import os\n\nfrom setuptools import setup, find_packages\n\nsetup(\n    name = \"xml2json\",\n    version = \"0.1\",\n    author = \"Hay Kranen\",\n    author_email = \"huskyr@gmail.com\",\n    description = (\"Python script converts XML to JSON or the other way around\"),\n    license = \"LICENSE\",\n    keywords = \"xml json\",\n    url = \"http://github.com/hay/xml2json\",\n    #packages=find_packages(exclude=['ez_setup']),\n    py_modules=['xml2json'],\n    classifiers=[\n        \"Development Status :: 3 - Alpha\",\n        \"Topic :: Utilities\",\n        \"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)\",\n        ],\n    install_requires=[\n        'simplejson'\n        ],\n    entry_points={\n        'console_scripts': [\n            'xml2json = xml2json:main'\n        ]\n    }\n)\n"
  },
  {
    "path": "test/__init__.py",
    "content": ""
  },
  {
    "path": "test/test_xml2json.py",
    "content": "import unittest\nimport xml2json\nimport optparse\nimport json\nimport os\n\nxmlstring = \"\"\noptions = None\n\nclass SimplisticTest(unittest.TestCase):\n\n    def setUp(self):\n        global xmlstring, options\n        filename = os.path.join(os.path.dirname(__file__), 'xml_ns2.xml')\n        xmlstring = open(filename).read()\n        options = optparse.Values({\"pretty\": False})\n\n    def test_default_namespace_attribute(self):\n        strip_ns = 0\n        json_string = xml2json.xml2json(xmlstring,options,strip_ns)\n        # check string\n        self.assertTrue(json_string.find(\"{http://www.w3.org/TR/html4/}table\") != -1)\n        self.assertTrue(json_string.find(\"{http://www.w3.org/TR/html4/}tr\") != -1)\n        self.assertTrue(json_string.find(\"@class\") != -1)\n\n        # check the simple name is not exist\n        json_data = json.loads(json_string)\n        self.assertFalse(\"table\" in json_data[\"root\"])\n\n    def test_strip_namespace(self):\n        strip_ns = 1\n        json_string = xml2json.xml2json(xmlstring,options,strip_ns)\n        json_data = json.loads(json_string)\n\n        # namespace is stripped\n        self.assertFalse(json_string.find(\"{http://www.w3.org/TR/html4/}table\") != -1)\n\n        # TODO , attribute shall be kept\n        #self.assertTrue(json_string.find(\"@class\") != -1)\n\n        #print json_data[\"root\"][\"table\"]\n        #print json_data[\"root\"][\"table\"][0][\"tr\"]\n        self.assertTrue(\"table\" in json_data[\"root\"])\n        self.assertEqual(json_data[\"root\"][\"table\"][0][\"tr\"][\"td\"] , [\"Apples\", \"Bananas\"])\n\nif __name__ == '__main__':\n    unittest.main()\n"
  },
  {
    "path": "test/xml_ns2.xml",
    "content": "<root>\n\n<h:table xmlns:h=\"http://www.w3.org/TR/html4/\">\n  <h:tr>\n    <h:td class=\"favorite\">Apples</h:td>\n    <h:td>Bananas</h:td>\n  </h:tr>\n</h:table>\n\n<f:table xmlns:f=\"http://www.w3schools.com/furniture\">\n  <f:name>African Coffee Table</f:name>\n  <f:width>80</f:width>\n  <f:length>120</f:length>\n</f:table>\n\n</root>\n"
  },
  {
    "path": "xml2json.py",
    "content": "#!/usr/bin/env python\n\n\"\"\"xml2json.py  Convert XML to JSON\n\nRelies on ElementTree for the XML parsing.  This is based on\npesterfish.py but uses a different XML->JSON mapping.\nThe XML->JSON mapping is described at\nhttp://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html\n\nRewritten to a command line utility by Hay Kranen < github.com/hay > with\ncontributions from George Hamilton (gmh04) and Dan Brown (jdanbrown)\n\nXML                              JSON\n<e/>                             \"e\": null\n<e>text</e>                      \"e\": \"text\"\n<e name=\"value\" />               \"e\": { \"@name\": \"value\" }\n<e name=\"value\">text</e>         \"e\": { \"@name\": \"value\", \"#text\": \"text\" }\n<e> <a>text</a ><b>text</b> </e> \"e\": { \"a\": \"text\", \"b\": \"text\" }\n<e> <a>text</a> <a>text</a> </e> \"e\": { \"a\": [\"text\", \"text\"] }\n<e> text <a>text</a> </e>        \"e\": { \"#text\": \"text\", \"a\": \"text\" }\n\nThis is very similar to the mapping used for Yahoo Web Services\n(http://developer.yahoo.com/common/json.html#xml).\n\nThis is a mess in that it is so unpredictable -- it requires lots of testing\n(e.g. to see if values are lists or strings or dictionaries).  For use\nin Python this could be vastly cleaner.  Think about whether the internal\nform can be more self-consistent while maintaining good external\ncharacteristics for the JSON.\n\nLook at the Yahoo version closely to see how it works.  Maybe can adopt\nthat completely if it makes more sense...\n\nR. White, 2006 November 6\n\"\"\"\n\nimport json\nimport optparse\nimport sys\nimport os\nfrom collections import OrderedDict\n\nimport xml.etree.cElementTree as ET\n\n\ndef strip_tag(tag):\n    strip_ns_tag = tag\n    split_array = tag.split('}')\n    if len(split_array) > 1:\n        strip_ns_tag = split_array[1]\n        tag = strip_ns_tag\n    return tag\n\n\ndef elem_to_internal(elem, strip_ns=1, strip=1):\n    \"\"\"Convert an Element into an internal dictionary (not JSON!).\"\"\"\n\n    d = OrderedDict()\n    elem_tag = elem.tag\n    if strip_ns:\n        elem_tag = strip_tag(elem.tag)\n    for key, value in list(elem.attrib.items()):\n        d['@' + key] = value\n\n    # loop over subelements to merge them\n    for subelem in elem:\n        v = elem_to_internal(subelem, strip_ns=strip_ns, strip=strip)\n\n        tag = subelem.tag\n        if strip_ns:\n            tag = strip_tag(subelem.tag)\n\n        value = v[tag]\n\n        try:\n            # add to existing list for this tag\n            d[tag].append(value)\n        except AttributeError:\n            # turn existing entry into a list\n            d[tag] = [d[tag], value]\n        except KeyError:\n            # add a new non-list entry\n            d[tag] = value\n    text = elem.text\n    tail = elem.tail\n    if strip:\n        # ignore leading and trailing whitespace\n        if text:\n            text = text.strip()\n        if tail:\n            tail = tail.strip()\n\n    if tail:\n        d['#tail'] = tail\n\n    if d:\n        # use #text element if other attributes exist\n        if text:\n            d[\"#text\"] = text\n    else:\n        # text is the value if no attributes\n        d = text or None\n    return {elem_tag: d}\n\n\ndef internal_to_elem(pfsh, factory=ET.Element):\n\n    \"\"\"Convert an internal dictionary (not JSON!) into an Element.\n\n    Whatever Element implementation we could import will be\n    used by default; if you want to use something else, pass the\n    Element class as the factory parameter.\n    \"\"\"\n\n    attribs = OrderedDict()\n    text = None\n    tail = None\n    sublist = []\n    tag = list(pfsh.keys())\n    if len(tag) != 1:\n        raise ValueError(\"Illegal structure with multiple tags: %s\" % tag)\n    tag = tag[0]\n    value = pfsh[tag]\n    if isinstance(value, dict):\n        for k, v in list(value.items()):\n            if k[:1] == \"@\":\n                attribs[k[1:]] = v\n            elif k == \"#text\":\n                text = v\n            elif k == \"#tail\":\n                tail = v\n            elif isinstance(v, list):\n                for v2 in v:\n                    sublist.append(internal_to_elem({k: v2}, factory=factory))\n            else:\n                sublist.append(internal_to_elem({k: v}, factory=factory))\n    else:\n        text = value\n    e = factory(tag, attribs)\n    for sub in sublist:\n        e.append(sub)\n    e.text = text\n    e.tail = tail\n    return e\n\n\ndef elem2json(elem, options, strip_ns=1, strip=1):\n\n    \"\"\"Convert an ElementTree or Element into a JSON string.\"\"\"\n\n    if hasattr(elem, 'getroot'):\n        elem = elem.getroot()\n\n    if options.pretty:\n        return json.dumps(elem_to_internal(elem, strip_ns=strip_ns, strip=strip), indent=4, separators=(',', ': '))\n    else:\n        return json.dumps(elem_to_internal(elem, strip_ns=strip_ns, strip=strip))\n\n\ndef json2elem(json_data, factory=ET.Element):\n\n    \"\"\"Convert a JSON string into an Element.\n\n    Whatever Element implementation we could import will be used by\n    default; if you want to use something else, pass the Element class\n    as the factory parameter.\n    \"\"\"\n\n    return internal_to_elem(json.loads(json_data), factory)\n\n\ndef xml2json(xmlstring, options, strip_ns=1, strip=1):\n\n    \"\"\"Convert an XML string into a JSON string.\"\"\"\n\n    elem = ET.fromstring(xmlstring)\n    return elem2json(elem, options, strip_ns=strip_ns, strip=strip)\n\n\ndef json2xml(json_data, factory=ET.Element):\n\n    \"\"\"Convert a JSON string into an XML string.\n\n    Whatever Element implementation we could import will be used by\n    default; if you want to use something else, pass the Element class\n    as the factory parameter.\n    \"\"\"\n    if not isinstance(json_data, dict):\n        json_data = json.loads(json_data)\n\n    elem = internal_to_elem(json_data, factory)\n    return ET.tostring(elem)\n\n\ndef main():\n    p = optparse.OptionParser(\n        description='Converts XML to JSON or the other way around.  Reads from standard input by default, or from file if given.',\n        prog='xml2json',\n        usage='%prog -t xml2json -o file.json [file]'\n    )\n    p.add_option('--type', '-t', help=\"'xml2json' or 'json2xml'\", default=\"xml2json\")\n    p.add_option('--out', '-o', help=\"Write to OUT instead of stdout\")\n    p.add_option(\n        '--strip_text', action=\"store_true\",\n        dest=\"strip_text\", help=\"Strip text for xml2json\")\n    p.add_option(\n        '--pretty', action=\"store_true\",\n        dest=\"pretty\", help=\"Format JSON output so it is easier to read\")\n    p.add_option(\n        '--strip_namespace', action=\"store_true\",\n        dest=\"strip_ns\", help=\"Strip namespace for xml2json\")\n    p.add_option(\n        '--strip_newlines', action=\"store_true\",\n        dest=\"strip_nl\", help=\"Strip newlines for xml2json\")\n    options, arguments = p.parse_args()\n\n    inputstream = sys.stdin\n    if len(arguments) == 1:\n        try:\n            inputstream = open(arguments[0])\n        except:\n            sys.stderr.write(\"Problem reading '{0}'\\n\".format(arguments[0]))\n            p.print_help()\n            sys.exit(-1)\n\n    input = inputstream.read()\n\n    strip = 0\n    strip_ns = 0\n    if options.strip_text:\n        strip = 1\n    if options.strip_ns:\n        strip_ns = 1\n    if options.strip_nl:\n        input = input.replace('\\n', '').replace('\\r','')\n    if (options.type == \"xml2json\"):\n        out = xml2json(input, options, strip_ns, strip)\n    else:\n        out = json2xml(input)\n\n    if (options.out):\n        file = open(options.out, 'w')\n        file.write(out)\n        file.close()\n    else:\n        print(out)\n\nif __name__ == \"__main__\":\n    main()\n\n"
  }
]