sax-jsvsxmltodict
sax-js is a streaming XML parser for Node.js that is built on top of the sax C library. It is designed to be fast, low-memory, and easy to use. It is commonly used for parsing large XML files, as it allows you to process the XML data incrementally, rather than loading the entire file into memory at once.
sax-js is a low-level html tree parser and does not provide html query capabilities (like CSS selectors) though it can be useful in HTML tree parsing and serialization.
xmltodict is a Python library that allows you to work with XML data as if it were JSON. It allows you to parse XML documents and convert them to dictionaries, which can then be easily manipulated using standard dictionary operations.
You can also use the library to convert a dictionary back into an XML document. xmltodict is built on top of the popular lxml library and provides a simple, intuitive API for working with XML data.
Note that despite using lxml conversion speeds can be quite slow for large XML documents and in web scraping this should be used to parse specific snippets instead of whole HTML documents.
xmltodict pairs well with JSON parsing tools like jmespath or jsonpath. Alternatively, it can be used in reverse mode to parse JSON documents using HTML parsing tools like CSS selectors and XPath.
It can be installed via pip by running pip install xmltodict
command.
Example Use
const fs = require("fs");
const sax = require("sax");
const xmlStream = fs.createReadStream("example.xml");
const saxParser = sax.createStream(true, {});
saxParser.on("opentag", function(node) {
console.log(`<${node.name}>`);
});
saxParser.on("closetag", function(nodeName) {
console.log(`</${nodeName}>`);
});
saxParser.on("text", function(text) {
console.log(text);
});
xmlStream.pipe(saxParser);
import xmltodict
xml_string = """
<book>
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<publisher>Charles Scribner's Sons</publisher>
<publication_date>1925</publication_date>
</book>
"""
book_dict = xmltodict.parse(xml_string)
print(book_dict)
{'book': {'title': 'The Great Gatsby',
'author': 'F. Scott Fitzgerald',
'publisher': "Charles Scribner's Sons",
'publication_date': '1925'}}
# and to reverse:
book_xml = xmltodict.unparse(book_dict)
print(book_xml)
# the xml can be loaded and parsed using parsel or beautifulsoup:
from parsel import Selector
sel = Selector(book_xml)
print(sel.css('publication_date::text').get())
'1925'