Repository: hay/xml2json
Branch: master
Commit: c01922797ebf
Files: 8
Total size: 14.0 KB
Directory structure:
gitextract_41pxzxjy/
├── .gitignore
├── LICENSE
├── README.md
├── setup.py
├── test/
│ ├── __init__.py
│ ├── test_xml2json.py
│ └── xml_ns2.xml
└── xml2json.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
*pyc
__pycache__/*
================================================
FILE: LICENSE
================================================
Copyright (C) 2010-2013, Hay Kranen
Permission 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:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE 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.
================================================
FILE: README.md
================================================
XML2JSON
========
**This module is deprecated and will not be updated anymore (May 2019)**
* To convert between text-based data formats (including XML and JSON) use my library [`dataknead`](http://github.com/hay/dataknead).
* To work with XML in Python i recommend the excellent [`xmltodict`](https://github.com/martinblech/xmltodict).
## Deprecated documentation
Python script converts XML to JSON or the other way around
Usage
-----
Make this executable
$ chmod +x xml2json
Then invoke it from the command line like this
$ xml2json -t xml2json -o file.json file.xml
Or the other way around
$ xml2json -t json2xml -o file.xml file.json
Without the `-o` parameter `xml2json` writes to stdout
$ xml2json -t json2xml file.json
Additional the options:
Strip text (#text and #tail) in the json
$ xml2json -t xml2json -o file.json file.xml --strip_text
Strip namespace in the json
$ xml2json -t xml2json -o file.json file.xml --strip_namespace
In code
from xml2json import json2xml
d = {'r': {'@p': 'p1', '#text': 't1', 'c': 't2'}}
print(json2xml(d))
> b'
XML JSON
<e/> "e": null
<e>text</e> "e": "text"
<e name="value" /> "e": { "@name": "value" }
<e name="value">text</e> "e": { "@name": "value", "#text": "text" }
<e> <a>text</a ><b>text</b> </e> "e": { "a": "text", "b": "text" }
<e> <a>text</a> <a>text</a> </e> "e": { "a": ["text", "text"] }
<e> text <a>text</a> </e> "e": { "#text": "text", "a": "text" }
This is very similar to the mapping used for [Yahoo Web Services](http://developer.yahoo.com/common/json.html#xml)
This 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.
Look at the Yahoo version closely to see how it works. Maybe can adopt that completely if it makes more sense...
R. White, 2006 November 6
================================================
FILE: setup.py
================================================
import os
from setuptools import setup, find_packages
setup(
name = "xml2json",
version = "0.1",
author = "Hay Kranen",
author_email = "huskyr@gmail.com",
description = ("Python script converts XML to JSON or the other way around"),
license = "LICENSE",
keywords = "xml json",
url = "http://github.com/hay/xml2json",
#packages=find_packages(exclude=['ez_setup']),
py_modules=['xml2json'],
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: Utilities",
"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
],
install_requires=[
'simplejson'
],
entry_points={
'console_scripts': [
'xml2json = xml2json:main'
]
}
)
================================================
FILE: test/__init__.py
================================================
================================================
FILE: test/test_xml2json.py
================================================
import unittest
import xml2json
import optparse
import json
import os
xmlstring = ""
options = None
class SimplisticTest(unittest.TestCase):
def setUp(self):
global xmlstring, options
filename = os.path.join(os.path.dirname(__file__), 'xml_ns2.xml')
xmlstring = open(filename).read()
options = optparse.Values({"pretty": False})
def test_default_namespace_attribute(self):
strip_ns = 0
json_string = xml2json.xml2json(xmlstring,options,strip_ns)
# check string
self.assertTrue(json_string.find("{http://www.w3.org/TR/html4/}table") != -1)
self.assertTrue(json_string.find("{http://www.w3.org/TR/html4/}tr") != -1)
self.assertTrue(json_string.find("@class") != -1)
# check the simple name is not exist
json_data = json.loads(json_string)
self.assertFalse("table" in json_data["root"])
def test_strip_namespace(self):
strip_ns = 1
json_string = xml2json.xml2json(xmlstring,options,strip_ns)
json_data = json.loads(json_string)
# namespace is stripped
self.assertFalse(json_string.find("{http://www.w3.org/TR/html4/}table") != -1)
# TODO , attribute shall be kept
#self.assertTrue(json_string.find("@class") != -1)
#print json_data["root"]["table"]
#print json_data["root"]["table"][0]["tr"]
self.assertTrue("table" in json_data["root"])
self.assertEqual(json_data["root"]["table"][0]["tr"]["td"] , ["Apples", "Bananas"])
if __name__ == '__main__':
unittest.main()
================================================
FILE: test/xml_ns2.xml
================================================