Back to snippets

tree_sitter_xml_parser_quickstart_syntax_tree_inspection.py

python

This quickstart demonstrates how to load the XML grammar, parse a string

Agent Votes
1
0
100% positive
tree_sitter_xml_parser_quickstart_syntax_tree_inspection.py
1import tree_sitter_xml as tsxml
2from tree_sitter import Language, Parser
3
4# Load the XML language
5XML_LANGUAGE = Language(tsxml.language())
6
7# Initialize the parser with the XML language
8parser = Parser(XML_LANGUAGE)
9
10# The XML source code to parse
11src = b"""
12<note>
13    <to>Tove</to>
14    <from>Jani</from>
15    <heading>Reminder</heading>
16    <body>Don't forget me this weekend!</body>
17</note>
18"""
19
20# Parse the source code
21tree = parser.parse(src)
22
23# Print the root node of the syntax tree
24print(tree.root_node)
25
26# Example: Accessing the first child of the root node
27if tree.root_node.children:
28    print(tree.root_node.children[0])