Xml2Json: XML to JSON Conversion Made Easy
Published on by Flutter News Hub
Xml2Json is a versatile package that enables the seamless conversion of XML data into JSON, catering to various JSON conventions. It utilizes the xml parser to parse XML data into a parse tree, which is then transformed into JSON based on specific transformation rules.
JSON Output Conventions
Xml2Json offers four JSON output conventions:
-
Parker: Lean and lossy, suitable for lightweight parsing of collections where attributes and namespaces are not crucial.
-
Badgerfish: Preserves XML attributes and namespaces, ideal for heavyweight parsing where detailed information is needed.
-
GData: Similar to Badgerfish but uses
$t
instead of$
for values and drops the@
symbol for attributes. -
OpenRally: Also preserves XML attributes and namespaces, but uses a
(key/value)
format for values.
Transformation Rules
Parker
- Element names become object properties, and text content goes into the
$
property. - Nested elements become nested properties.
- Consecutive elements with the same name are grouped under that name, allowing easy extraction.
Badgerfish
- Element names become object properties.
- Text content goes into the
$
property. - Attributes go in properties starting with
@
. - Multiple attributes become array elements.
- Namespaces are placed in the
@xmlns
property.
GData
- Similar to Badgerfish but uses
$t
instead of$
for values and drops the@
symbol for attributes.
OpenRally
- Similar to Badgerfish but uses a
(key/value)
format for values.
Global Rules
- All JSON output is in string format.
- XML comments and CDATA sections are ignored for Parker, while CDATA sections are converted to
__cdata
properties for Badgerfish and GData.
Usage Example
import 'package:xml2json/xml2json.dart';
void main() {
// XML input
String xml = '''
1
2
three
''';
// Create an instance of the Xml2Json class
Xml2Json xml2Json = Xml2Json();
// Transform the XML into JSON using the Parker convention
String json = xml2Json.transform(xml);
// Print the JSON output
print(json);
// Output: {"item":["1","2","three"]}
}
Conclusion
Xml2Json provides a convenient and customizable solution for converting XML data into JSON. Its powerful transformation engine supports various JSON conventions, making it a valuable tool for data exchange and integration scenarios.