### pyxform_validator_update CLI Examples
Source: https://context7.com/xlsform/pyxform/llms.txt
Command-line tool to manage ODK Validate JAR and Enketo Validate binary installations.
```bash
# Update ODK Validate to a specific release
pyxform_validator_update odk update ODK-Validate-v2.0.0.jar
```
```bash
# Check currently installed ODK Validate version
pyxform_validator_update odk info
```
```bash
# Download / update Enketo Validate (not bundled by default)
pyxform_validator_update enketo update
```
```bash
# Check Enketo Validate installation
pyxform_validator_update enketo info
```
--------------------------------
### Install pyxform with development dependencies
Source: https://github.com/xlsform/pyxform/blob/master/README.rst
Installs pyxform in editable mode along with development-specific dependencies, required for contributing to the project.
```bash
pip install -e .[dev]
```
--------------------------------
### Install pyxform from remote source (master branch)
Source: https://github.com/xlsform/pyxform/blob/master/README.rst
Installs pyxform directly from the master branch of the GitHub repository. Use this only if pre-release code is desired.
```bash
pip install git+https://github.com/XLSForm/pyxform.git@master#egg=pyxform
```
--------------------------------
### Clone pyxform repository and set up development environment
Source: https://github.com/xlsform/pyxform/blob/master/README.rst
Steps to clone the pyxform repository, create a virtual environment, and install pyxform in editable mode for development. Requires Java 8 or newer.
```bash
# Get a copy of the repository.
mkdir -P ~/repos/pyxform
cd ~/repos/pyxform
git clone https://github.com/XLSForm/pyxform.git repo
# Create and activate a virtual environment for the install.
/usr/local/bin/python -m venv venv
. venv/bin/activate
# Install the pyxform and it's production dependencies.
(venv)$ cd repo
# If this doesn't work, upgrade pip ``pip install --upgrade pip`` and retry.
(venv)$ pip install -e .
(venv)$ python pyxform/xls2xform.py --help
(venv)$ xls2xform --help # same effect as previous line
(venv)$ which xls2xform # ~/repos/pyxform/venv/bin/xls2xform
```
--------------------------------
### Install pyxform using pip
Source: https://github.com/xlsform/pyxform/blob/master/README.rst
Installs the latest official release of pyxform. This command can be used for general form conversion tasks.
```bash
pip install pyxform
```
--------------------------------
### Run xls2xform from command line
Source: https://github.com/xlsform/pyxform/blob/master/README.rst
Converts an XLSForm file to ODK XForms format using the installed pyxform package. The output path is optional.
```bash
xls2xform path_to_XLSForm [output_path]
```
--------------------------------
### `xls2xform` CLI — Command-line conversion tool
Source: https://context7.com/xlsform/pyxform/llms.txt
A command-line interface tool installed as a console script. It allows for converting XLSForm files to XForm XML directly from the terminal, with options to control validation and output formatting.
```APIDOC
## `xls2xform` CLI — Command-line conversion tool
Installed as a console script when pyxform is installed via pip. Converts an XLSForm file to XForm XML from the terminal, with flags to control validators and output formatting.
```bash
# Basic conversion (ODK Validate runs by default)
xls2xform path/to/my_form.xlsx
# Specify explicit output path
xls2xform path/to/my_form.xlsx path/to/output/my_form.xml
# Skip all external validation (faster, no Java required)
xls2xform my_form.xlsx --skip_validate
# Run only Enketo Validate (requires Enketo binary installed)
xls2xform my_form.xlsx --enketo_validate --skip_validate=False
# Run both ODK and Enketo validators
xls2xform my_form.xlsx --odk_validate --enketo_validate
# Output result as JSON (useful for programmatic consumption)
xls2xform my_form.xlsx --json
# stdout: {"code": 100, "message": "Ok!", "warnings": []}
```
```
--------------------------------
### Check XForm Validity with ODK Validate
Source: https://github.com/xlsform/pyxform/blob/master/pyxform/validators/odk_validate/README.rst
Import the `odk_validate` library and use the `check_xform` function to get a list of warnings for an XForm file. An empty list indicates a valid XForm with no warnings.
```python
import odk_validate
xform_warnings = odk_validate.check_xform("/path/to/xform.xml")
if len(xform_warnings) == 0:
print "Your XForm is valid with no warnings!"
else:
print "Your XForm is valid but has warnings"
print xform_warnings
```
--------------------------------
### Validate XForm with Enketo Validate
Source: https://context7.com/xlsform/pyxform/llms.txt
Runs the Enketo Validate binary. Ensure it's downloaded separately. Returns warnings or raises `EnketoValidateError`.
```python
from pyxform.validators.enketo_validate import check_xform, EnketoValidateError, install_exists
if not install_exists():
print("Enketo Validate is not installed. Run: pyxform_validator_update enketo update")
else:
try:
warnings = check_xform("my_form.xml")
print("Enketo validation passed, warnings:", warnings)
except EnketoValidateError as e:
print("Enketo validation failed:", e)
```
--------------------------------
### enketo_validate.check_xform()
Source: https://context7.com/xlsform/pyxform/llms.txt
Validates an XForm file using the Enketo Validate binary. The binary must be downloaded separately. Returns warnings on success or raises an EnketoValidateError.
```APIDOC
## `enketo_validate.check_xform()` — Validate an XForm with Enketo Validate
Runs the Enketo Validate binary (must be downloaded separately via the updater tool) against an XForm file. Returns warnings on success or raises `EnketoValidateError`.
```python
from pyxform.validators.enketo_validate import check_xform, EnketoValidateError, install_exists
if not install_exists():
print("Enketo Validate is not installed. Run: pyxform_validator_update enketo update")
else:
try:
warnings = check_xform("my_form.xml")
print("Enketo validation passed, warnings:", warnings)
except EnketoValidateError as e:
print("Enketo validation failed:", e)
```
```
--------------------------------
### Deactivate and reactivate virtual environment
Source: https://github.com/xlsform/pyxform/blob/master/README.rst
Commands to exit a virtual environment and then reactivate it, demonstrating how the PATH changes for the xls2xform command.
```bash
(venv)$ deactivate # leave the venv, scripts not on $PATH
$ xls2xform --help
# -bash: xls2xform: command not found
$ . ~/repos/pyxform/venv/bin/activate # reactivate the venv
(venv)$ which xls2xform # scripts available on $PATH again
~/repos/pyxform/venv/bin/xls2xform
```
--------------------------------
### `convert()` — In-memory XLSForm to XForm conversion
Source: https://context7.com/xlsform/pyxform/llms.txt
The primary library entry point for in-memory conversion. Accepts various input formats (file path, bytes, file-like object, dict) and returns a `ConvertResult` object containing the XForm XML, warnings, and itemsets.
```APIDOC
## `convert()` — In-memory XLSForm to XForm conversion
The primary library entry point. Accepts a file path, raw bytes, a file-like object, or a pre-parsed `dict`, and returns a `ConvertResult` dataclass with `xform` (XML string), `warnings` (list), `itemsets` (CSV string for external choices), `_pyxform` (internal dict), and `_survey` (internal `Survey` object). Avoids any file I/O for the output, making it suitable for server or pipeline usage.
```python
from pyxform.xls2xform import convert, ConvertResult
# --- Convert from a file path ---
warnings: list[str] = []
result: ConvertResult = convert(
xlsform="my_survey.xlsx",
warnings=warnings,
validate=False, # skip ODK Validate (requires Java)
pretty_print=True, # human-readable XML output
enketo=False, # skip Enketo Validate
form_name="my_survey",
default_language="English",
)
print(result.xform) # full XForm XML string
print(result.warnings) # e.g. ["Row 4: Group has no label: ..."]
print(result.itemsets) # None, or CSV string if external choices present
# --- Convert from bytes (e.g. from a web upload) ---
with open("my_survey.xlsx", "rb") as f:
file_bytes = f.read()
result2 = convert(xlsform=file_bytes, file_type="xlsx")
print(result2.xform[:200])
# --- Convert with ODK Validate enabled (requires Java 8+) ---
try:
result3 = convert(xlsform="my_survey.xlsx", validate=True)
except OSError as e:
print(f"Java not found: {e}")
from pyxform.validators.odk_validate import ODKValidateError
try:
result3 = convert(xlsform="invalid_form.xlsx", validate=True)
except ODKValidateError as e:
print(f"XForm is invalid: {e}")
# --- Convert from a pre-parsed dict (bypasses file reading) ---
survey_dict = {
"survey": [
{"type": "text", "name": "full_name", "label": "What is your name?"},
{"type": "integer", "name": "age", "label": "How old are you?"},
],
"choices": [],
"settings": [{"form_title": "Demo Form", "form_id": "demo"}],
}
result4 = convert(xlsform=survey_dict)
print(result4.xform[:300])
```
```
--------------------------------
### Run pyxform tests
Source: https://github.com/xlsform/pyxform/blob/master/README.rst
Executes the test suite for pyxform using Python's built-in unittest module.
```bash
python -m unittest
```
--------------------------------
### Pyxform CLI Tool Usage
Source: https://context7.com/xlsform/pyxform/llms.txt
The `xls2xform` command-line tool provides a convenient way to convert XLSForm files from the terminal. It supports specifying output paths, skipping validation, and enabling specific validators like ODK Validate and Enketo Validate. The `--json` flag outputs results in a machine-readable format.
```bash
# Basic conversion (ODK Validate runs by default)
xls2xform path/to/my_form.xlsx
# Specify explicit output path
xls2xform path/to/my_form.xlsx path/to/output/my_form.xml
# Skip all external validation (faster, no Java required)
xls2xform my_form.xlsx --skip_validate
# Run only Enketo Validate (requires Enketo binary installed)
xls2xform my_form.xlsx --enketo_validate --skip_validate=False
# Run both ODK and Enketo validators
xls2xform my_form.xlsx --odk_validate --enketo_validate
# Output result as JSON (useful for programmatic consumption)
xls2xform my_form.xlsx --json
# stdout: {"code": 100, "message": "Ok!", "warnings": []}
```
--------------------------------
### create_survey_from_path()
Source: https://context7.com/xlsform/pyxform/llms.txt
Builds a Survey object from an XLS/XLSX file, with support for directory-level includes. It loads compatible XLSForm files in the same directory, allowing sections from sibling files to be referenced.
```APIDOC
## `create_survey_from_path()` — Build a Survey with directory-level include support
Like `create_survey_from_xls()` but supports the `include_directory` flag, which loads all compatible XLSForm files in the same directory so that sections from sibling files can be referenced via the `include` type in the survey sheet.
```python
from pyxform.builder import create_survey_from_path
# Single file conversion
survey = create_survey_from_path("forms/my_form.xlsx")
# With directory includes (all xlsx/xls in the directory are loaded as sections)
survey_with_includes = create_survey_from_path(
"forms/my_form.xlsx",
include_directory=True,
)
xml_str = survey_with_includes.to_xml(pretty_print=True)
```
```
--------------------------------
### Format and lint pyxform code with ruff
Source: https://github.com/xlsform/pyxform/blob/master/README.rst
Applies code formatting and linting checks using the 'ruff' tool to the pyxform project and its tests.
```bash
ruff format pyxform tests
ruff check pyxform tests
```
--------------------------------
### Create Survey object with directory include support
Source: https://context7.com/xlsform/pyxform/llms.txt
Utilize `create_survey_from_path` to build a Survey object, supporting directory-level includes. This function loads all compatible XLSForm files in a specified directory, enabling cross-file references via the 'include' type.
```python
from pyxform.builder import create_survey_from_path
# Single file conversion
survey = create_survey_from_path("forms/my_form.xlsx")
# With directory includes (all xlsx/xls in the directory are loaded as sections)
survey_with_includes = create_survey_from_path(
"forms/my_form.xlsx",
include_directory=True,
)
xml_str = survey_with_includes.to_xml(pretty_print=True)
```
--------------------------------
### Validate XForm with ODK Validate
Source: https://context7.com/xlsform/pyxform/llms.txt
Runs the bundled ODK Validate JAR. Requires Java 8+ on the system PATH. Returns warnings or raises `ODKValidateError` for invalid forms.
```python
from pyxform.validators.odk_validate import check_xform, ODKValidateError
import tempfile, os
xform_xml = "..." # full XForm XML
# Write to a temp file for validation
with tempfile.NamedTemporaryFile(suffix=".xml", mode="w", delete=False) as f:
f.write(xform_xml)
tmp_path = f.name
try:
warnings = check_xform(tmp_path)
if warnings:
print("Validation warnings:", warnings)
else:
print("XForm is valid.")
except ODKValidateError as e:
print("XForm is INVALID:", e)
except OSError as e:
print("Java not available:", e)
finally:
os.unlink(tmp_path)
```
--------------------------------
### File-based XLSForm to XForm Conversion with `xls2xform_convert()`
Source: https://context7.com/xlsform/pyxform/llms.txt
Use `xls2xform_convert()` for direct file-to-file conversion, writing the XForm XML to a specified path. It also automatically creates an `itemsets.csv` if external choice itemsets are used. Validation is enabled by default.
```python
from pyxform.xls2xform import xls2xform_convert
warnings = xls2xform_convert(
xlsform_path="household_survey.xlsx",
xform_path="household_survey.xml",
validate=True, # run ODK Validate (default True)
pretty_print=True, # indent output XML (default True)
enketo=False,
)
if warnings:
for w in warnings:
print("Warning:", w)
else:
print("Conversion successful with no warnings.")
# Output file: household_survey.xml
# If external choices present: itemsets.csv written alongside the XML
```
--------------------------------
### `xls2xform_convert()` — File-based conversion writing output to disk
Source: https://context7.com/xlsform/pyxform/llms.txt
Wraps the `convert()` function to handle file I/O. Reads from a specified XLSForm path and writes the resulting XForm XML to a specified output path. It also handles writing `itemsets.csv` for external choices.
```APIDOC
## `xls2xform_convert()` — File-based conversion writing output to disk
Wraps `convert()` with file I/O: reads from `xlsform_path` and writes the resulting XForm XML to `xform_path`. If the form uses external choice itemsets, an `itemsets.csv` is automatically written next to the output XML. Returns the list of conversion warnings.
```python
from pyxform.xls2xform import xls2xform_convert
warnings = xls2xform_convert(
xlsform_path="household_survey.xlsx",
xform_path="household_survey.xml",
validate=True, # run ODK Validate (default True)
pretty_print=True, # indent output XML (default True)
enketo=False,
)
if warnings:
for w in warnings:
print("Warning:", w)
else:
print("Conversion successful with no warnings.")
# Output file: household_survey.xml
# If external choices present: itemsets.csv written alongside the XML
```
```
--------------------------------
### Test XLSForm with PyxformTestCase
Source: https://context7.com/xlsform/pyxform/llms.txt
Test helper for XLSForm unit tests. Compiles an XLSForm (as Markdown table) and asserts properties of the resulting XForm.
```python
from tests.pyxform_test_case import PyxformTestCase
class MyFormTest(PyxformTestCase):
def test_required_field_generates_bind(self):
self.assertPyxformXform(
md="""
| survey | | | | |
| | type | name | label | required |
| | text | full_name | What is your name? | yes |
| | integer| age | How old are you? |
""",
xml__xpath_match=[
# Verify required bind is generated for full_name
"/h:html/h:head/x:model/x:bind[@nodeset='/test_name/full_name'][@required='true()']",
# Verify age has no required bind attribute
"/h:html/h:head/x:model/x:bind[@nodeset='/test_name/age'][not(@required)]",
],
)
def test_select_one_generates_choices(self):
self.assertPyxformXform(
md="""
| survey | | | |
| | type | name | label |
| | select_one yn | agree | Do you agree? |
| choices | | | |
| | list_name | name | label |
| | yn | yes | Yes |
| | yn | no | No |
""",
xml__xpath_count=[
(".//x:select1", 1), # one select1 control in body
(".//x:item", 2), # two items in the secondary instance
],
)
def test_invalid_form_raises_error(self):
self.assertPyxformXform(
md="""
| survey | | | |
| | type | name | label |
| | text | | Name? |
""",
errored=True,
error__contains=["name"],
)
```
--------------------------------
### In-memory XLSForm to XForm Conversion with `convert()`
Source: https://context7.com/xlsform/pyxform/llms.txt
Use the `convert()` function for in-memory conversion from various input types like file paths, bytes, or pre-parsed dictionaries. It returns a `ConvertResult` object containing the XForm XML, warnings, and itemsets. Set `validate=True` to enable ODK Validate, which requires Java.
```python
from pyxform.xls2xform import convert, ConvertResult
# --- Convert from a file path ---
warnings: list[str] = []
result: ConvertResult = convert(
xlsform="my_survey.xlsx",
warnings=warnings,
validate=False, # skip ODK Validate (requires Java)
pretty_print=True, # human-readable XML output
enketo=False, # skip Enketo Validate
form_name="my_survey",
default_language="English",
)
print(result.xform) # full XForm XML string
print(result.warnings) # e.g. ["Row 4: Group has no label: ..."]
print(result.itemsets) # None, or CSV string if external choices present
# --- Convert from bytes (e.g. from a web upload) ---
with open("my_survey.xlsx", "rb") as f:
file_bytes = f.read()
result2 = convert(xlsform=file_bytes, file_type="xlsx")
print(result2.xform[:200])
# --- Convert with ODK Validate enabled (requires Java 8+) ---
try:
result3 = convert(xlsform="my_survey.xlsx", validate=True)
except OSError as e:
print(f"Java not found: {e}")
from pyxform.validators.odk_validate import ODKValidateError
try:
result3 = convert(xlsform="invalid_form.xlsx", validate=True)
except ODKValidateError as e:
print(f"XForm is invalid: {e}")
# --- Convert from a pre-parsed dict (bypasses file reading) ---
survey_dict = {
"survey": [
{"type": "text", "name": "full_name", "label": "What is your name?"},
{"type": "integer", "name": "age", "label": "How old are you?"},
],
"choices": [],
"settings": [{"form_title": "Demo Form", "form_id": "demo"}],
}
result4 = convert(xlsform=survey_dict)
print(result4.xform[:300])
```
--------------------------------
### pyxform_validator_update CLI
Source: https://context7.com/xlsform/pyxform/llms.txt
A command-line tool to manage the download and update of bundled validators, including the ODK Validate JAR and the optional Enketo Validate binary.
```APIDOC
## `pyxform_validator_update` CLI — Update bundled validators
Command-line tool to download or update the ODK Validate JAR and the optional Enketo Validate binary from their respective GitHub releases.
```bash
# Update ODK Validate to a specific release
pyxform_validator_update odk update ODK-Validate-v2.0.0.jar
# Check currently installed ODK Validate version
pyxform_validator_update odk info
# Download / update Enketo Validate (not bundled by default)
pyxform_validator_update enketo update
# Check Enketo Validate installation
pyxform_validator_update enketo info
```
```
--------------------------------
### create_survey()
Source: https://context7.com/xlsform/pyxform/llms.txt
Constructs a Survey object directly from a pyxform-format JSON dictionary. This is useful for programmatic form construction or testing without an XLS file.
```APIDOC
## `create_survey()` — Build a Survey from a pre-built JSON dictionary
Constructs a `Survey` object directly from a pyxform-format JSON dictionary (the same intermediate format produced by `workbook_to_json()`). Useful for programmatic form construction or testing without an XLS file.
```python
from pyxform.builder import create_survey
main_section = {
"type": "survey",
"name": "registration",
"title": "Household Registration",
"children": [
{
"type": "text",
"name": "respondent_name",
"label": "Respondent name",
"bind": {"required": "true()"},
},
{
"type": "select one",
"name": "gender",
"label": "Gender",
"children": [
{"name": "male", "label": "Male"},
{"name": "female", "label": "Female"},
],
},
{
"type": "integer",
"name": "age",
"label": "Age",
"bind": {"constraint": ". > 0 and . < 150"},
},
],
}
survey = create_survey(
main_section=main_section,
id_string="registration_v1",
title="Household Registration",
)
print(survey.to_xml(pretty_print=True))
```
```
--------------------------------
### create_survey_from_xls()
Source: https://context7.com/xlsform/pyxform/llms.txt
Builds a Survey object from an XLS/XLSX file. This low-level function is useful for programmatic inspection or manipulation of the survey tree before serializing to XML.
```APIDOC
## `create_survey_from_xls()` — Build a Survey object from an XLS/XLSX file
Low-level builder function that reads an XLSForm file and returns a `Survey` object (the internal object model root). Useful when you need to programmatically inspect or manipulate the survey tree before serialising to XML.
```python
from pyxform.builder import create_survey_from_xls
survey = create_survey_from_xls("my_form.xlsx")
print(survey.title) # Form title from settings sheet
print(survey.id_string) # Form ID
print(len(survey.children)) # Number of top-level questions/groups
# Serialise to XML manually
xml_str = survey.to_xml(validate=False, pretty_print=True)
print(xml_str[:500])
# Inspect children
for child in survey.children:
print(child.name, child.type)
```
```
--------------------------------
### odk_validate.check_xform()
Source: https://context7.com/xlsform/pyxform/llms.txt
Validates an XForm XML file using the bundled ODK Validate JAR. It returns a list of warnings on success or raises an ODKValidateError if the form is invalid. Requires Java 8 or later.
```APIDOC
## `odk_validate.check_xform()` — Validate an XForm with ODK Validate
Runs the bundled ODK Validate JAR against a saved XForm XML file. Returns a list of warning strings on success, or raises `ODKValidateError` if the form is invalid. Requires Java 8 or later on the system PATH.
```python
from pyxform.validators.odk_validate import check_xform, ODKValidateError
import tempfile, os
xform_xml = """...""" # full XForm XML
# Write to a temp file for validation
with tempfile.NamedTemporaryFile(suffix=".xml", mode="w", delete=False) as f:
f.write(xform_xml)
tmp_path = f.name
try:
warnings = check_xform(tmp_path)
if warnings:
print("Validation warnings:", warnings)
else:
print("XForm is valid.")
except ODKValidateError as e:
print("XForm is INVALID:", e)
except OSError as e:
print("Java not available:", e)
finally:
os.unlink(tmp_path)
```
```
--------------------------------
### Create Survey object from XLS/XLSX file
Source: https://context7.com/xlsform/pyxform/llms.txt
Use `create_survey_from_xls` to build a Survey object from an XLSForm file. This is useful for programmatic inspection or manipulation of the survey structure before XML serialization. It allows access to the form's title, ID, and top-level elements.
```python
from pyxform.builder import create_survey_from_xls
survey = create_survey_from_xls("my_form.xlsx")
print(survey.title) # Form title from settings sheet
print(survey.id_string) # Form ID
print(len(survey.children)) # Number of top-level questions/groups
# Serialise to XML manually
xml_str = survey.to_xml(validate=False, pretty_print=True)
print(xml_str[:500])
# Inspect children
for child in survey.children:
print(child.name, child.type)
```
--------------------------------
### PyxformTestCase.assertPyxformXform()
Source: https://context7.com/xlsform/pyxform/llms.txt
A test helper method for XLSForm unit tests. It compiles an XLSForm provided as a Markdown table string and asserts properties of the generated XForm using XPath expressions or string matching.
```APIDOC
## `PyxformTestCase.assertPyxformXform()` — Test helper for XLSForm unit tests
A test base class used throughout pyxform's own test suite. Accepts an XLSForm written as a Markdown table string (`md`), compiles it, and asserts properties of the resulting XForm using XPath expressions or string matching. Available for downstream projects that test forms.
```python
from tests.pyxform_test_case import PyxformTestCase
class MyFormTest(PyxformTestCase):
def test_required_field_generates_bind(self):
self.assertPyxformXform(
md="""
| survey | | | | |
| | type | name | label | required |
| | text | full_name | What is your name? | yes |
| | integer| age | How old are you? | |
""",
xml__xpath_match=[
# Verify required bind is generated for full_name
"/h:html/h:head/x:model/x:bind[@nodeset='/test_name/full_name'][@required='true()']",
# Verify age has no required bind attribute
"/h:html/h:head/x:model/x:bind[@nodeset='/test_name/age'][not(@required)]",
],
)
def test_select_one_generates_choices(self):
self.assertPyxformXform(
md="""
| survey | | | |
| | type | name | label |
| | select_one yn | agree | Do you agree? |
| choices | | | |
| | list_name | name | label |
| | yn | yes | Yes |
| | yn | no | No |
""",
xml__xpath_count=[
(".//x:select1", 1), # one select1 control in body
(".//x:item", 2), # two items in the secondary instance
],
)
def test_invalid_form_raises_error(self):
self.assertPyxformXform(
md="""
| survey | | | |
| | type | name | label |
| | text | | Name? |
""",
errored=True,
error__contains=["name"],
)
```
```
--------------------------------
### workbook_to_json()
Source: https://context7.com/xlsform/pyxform/llms.txt
Transforms parsed workbook data (DefinitionData object) into the intermediate pyxform JSON dictionary. This is the core translation step between the spreadsheet representation and the object model.
```APIDOC
## `workbook_to_json()` — Convert parsed workbook data to pyxform JSON dict
Transforms a `DefinitionData` object (the raw parsed sheet rows) into the intermediate pyxform JSON dictionary. This is the core translation step between the spreadsheet representation and the object model. Called internally by `convert()` but available for direct use in custom pipelines.
```python
from pyxform.xls2json import workbook_to_json
from pyxform.xls2json_backends import get_xlsform
workbook = get_xlsform(xlsform="my_form.xlsx")
warnings: list[str] = []
json_dict = workbook_to_json(
workbook_dict=workbook,
form_name="my_form",
fallback_form_name=workbook.fallback_form_name,
default_language="English",
warnings=warnings,
)
print(json_dict["name"]) # root survey name
print(json_dict["title"]) # form title
print(len(json_dict["children"])) # number of top-level elements
print(warnings) # any translation or structural warnings
```
```
--------------------------------
### get_xlsform()
Source: https://context7.com/xlsform/pyxform/llms.txt
Parses an XLS, XLSX, or CSV file into raw sheet data, returning a DefinitionData dataclass. It supports auto-detection of file type or explicit override.
```APIDOC
## `get_xlsform()` — Parse an XLSForm file into raw sheet data
Reads an XLS, XLSX, or CSV file (or bytes/file-like object) and returns a `DefinitionData` dataclass containing the raw rows from each named sheet (`survey`, `choices`, `settings`, `external_choices`, `entities`, `osm`). Supports auto-detection of file type or explicit `file_type` override.
```python
from pyxform.xls2json_backends import get_xlsform, SupportedFileTypes
# From a file path (type auto-detected from extension)
workbook = get_xlsform(xlsform="my_form.xlsx")
print(workbook.survey[0]) # first row of survey sheet as dict
print(workbook.choices[:2]) # first two rows of choices sheet
print(workbook.settings) # settings sheet rows
print(workbook.fallback_form_name) # derived from filename
# From bytes with explicit type
with open("my_form.xlsx", "rb") as f:
raw = f.read()
workbook2 = get_xlsform(xlsform=raw, file_type=SupportedFileTypes.xlsx.value)
# From a CSV XLSForm
workbook3 = get_xlsform(xlsform="my_form.csv", file_type=SupportedFileTypes.csv.value)
```
```
--------------------------------
### Create Survey object from JSON dictionary
Source: https://context7.com/xlsform/pyxform/llms.txt
Use `create_survey` to construct a Survey object directly from a pyxform-format JSON dictionary. This is ideal for programmatic form construction or testing when an XLS file is not available. The function takes a main section dictionary and optional ID string and title.
```python
from pyxform.builder import create_survey
main_section = {
"type": "survey",
"name": "registration",
"title": "Household Registration",
"children": [
{
"type": "text",
"name": "respondent_name",
"label": "Respondent name",
"bind": {"required": "true()"},
},
{
"type": "select one",
"name": "gender",
"label": "Gender",
"children": [
{"name": "male", "label": "Male"},
{"name": "female", "label": "Female"},
],
},
{
"type": "integer",
"name": "age",
"label": "Age",
"bind": {"constraint": ". > 0 and . < 150"},
},
],
}
survey = create_survey(
main_section=main_section,
id_string="registration_v1",
title="Household Registration",
)
print(survey.to_xml(pretty_print=True))
```
--------------------------------
### Convert parsed workbook data to pyxform JSON
Source: https://context7.com/xlsform/pyxform/llms.txt
The `workbook_to_json` function transforms raw parsed sheet data (DefinitionData object) into the intermediate pyxform JSON dictionary. This is a core translation step, useful for custom pipelines. It accepts the workbook dictionary and form details, returning the JSON structure and any warnings encountered.
```python
from pyxform.xls2json import workbook_to_json
from pyxform.xls2json_backends import get_xlsform
workbook = get_xlsform(xlsform="my_form.xlsx")
warnings: list[str] = []
json_dict = workbook_to_json(
workbook_dict=workbook,
form_name="my_form",
fallback_form_name=workbook.fallback_form_name,
default_language="English",
warnings=warnings,
)
print(json_dict["name"]) # root survey name
print(json_dict["title"]) # form title
print(len(json_dict["children"])) # number of top-level elements
print(warnings) # any translation or structural warnings
```
--------------------------------
### Parse XLSForm file into raw sheet data
Source: https://context7.com/xlsform/pyxform/llms.txt
Use `get_xlsform` to parse XLS, XLSX, or CSV files into a `DefinitionData` object containing raw sheet rows. It supports auto-detection of file types or explicit overrides. This function is essential for reading XLSForm data before further processing.
```python
from pyxform.xls2json_backends import get_xlsform, SupportedFileTypes
# From a file path (type auto-detected from extension)
workbook = get_xlsform(xlsform="my_form.xlsx")
print(workbook.survey[0]) # first row of survey sheet as dict
print(workbook.choices[:2]) # first two rows of choices sheet
print(workbook.settings) # settings sheet rows
print(workbook.fallback_form_name) # derived from filename
# From bytes with explicit type
with open("my_form.xlsx", "rb") as f:
raw = f.read()
workbook2 = get_xlsform(xlsform=raw, file_type=SupportedFileTypes.xlsx.value)
# From a CSV XLSForm
workbook3 = get_xlsform(xlsform="my_form.csv", file_type=SupportedFileTypes.csv.value)
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.