# Python XML libraries

Python XML libraries parse XML documents into trees or dictionaries and write XML back out. An incremental parser processes a large document in steps rather than waiting for the whole input. These libraries let apps read feeds, configuration files, and API responses from services that return XML.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [lxml](#lxml) | 445.4M | 3.1K | Sep 2026 | BSD-3-Clause |
| [Beautiful Soup](#beautiful-soup) | 320.8M | Not on GitHub | Jun 2026 | MIT |
| [defusedxml](#defusedxml) | 276.9M | 559 | Mar 2021 | PSF-2.0 |
| [xmltodict](#xmltodict) | 116.3M | 5.8K | Feb 2026 | MIT |
| [xmlschema](#xmlschema) | 7.6M | 475 | Jun 2026 | MIT |
| [xsdata](#xsdata) | 3.6M | 457 | Oct 2026 | MIT |
| [pydantic-xml](#pydantic-xml) | 3.1M | 257 | Oct 2026 | Unlicense |
| [untangle](#untangle) | 321.6K | 628 | Sep 2026 | MIT |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[lxml](#lxml) has the most monthly downloads in this comparison, at 445.4M.

## Capabilities

| Library | Native XSD validation | Nested dictionary output | Namespace URI matching |
| --- | --- | --- | --- |
| [lxml](#lxml) | Yes | No | Yes |
| [Beautiful Soup](#beautiful-soup) | No | No | Via plugin |
| [defusedxml](#defusedxml) | No | No | Yes |
| [xmltodict](#xmltodict) | No | Yes | Yes |
| [xmlschema](#xmlschema) | Yes | Yes | Yes |
| [xsdata](#xsdata) | No | Yes | Yes |
| [pydantic-xml](#pydantic-xml) | No | Yes | Yes |
| [untangle](#untangle) | No | No | No |

## Libraries

### lxml

[GitHub](https://github.com/lxml/lxml) · [PyPI](https://pypi.org/project/lxml) · [Docs](https://pypi.org/project/lxml/)

Parses, edits, and serializes XML trees with the ElementTree API.

- Downloads / mo: 445.4M
- Stars: 3.1K
- Last release: 6.1.3
- License: BSD-3-Clause
- Capabilities: [From the lxml docs](https://pypi.org/project/lxml/)

**Strengths**

- **Builds and edits XML trees.** Create elements, modify the tree, and serialize XML through ElementTree APIs.
- **Parses large inputs incrementally.** Process input in steps rather than waiting for the entire document.

**Watch out for**

- **Streaming still builds a tree.** Clear processed elements when large inputs should not remain in memory.

```sh
pip install lxml
```

**scrapy/parsel** (1.4K stars)

[scrapy/parsel](https://github.com/scrapy/parsel) 

```python
def create_root_node(
    text: str,
    parser_cls: type[_ParserType],
    base_url: str | None = None,
    huge_tree: bool = True,
    body: bytes = b"",
    encoding: str = "utf-8",
) -> etree._Element:
    """Create root node for text using given parser class."""
    if text:
        body = text.strip().replace("\x00", "").encode(encoding) or b"<html/>"
    elif codecs.lookup(encoding).name != "utf-8":
        # lxml handles bytes that the declared encoding cannot decode by
        # truncating the document there, and characters that span several
        # bytes, as in UTF-16, are broken by the null and whitespace stripping
        # below. Only UTF-8 bytes are passed as is, since lxml does report
        # invalid UTF-8, and it covers most input.
        return _root_from_decoded_body(body, parser_cls, base_url, huge_tree, encoding)
    else:
        body = body.replace(b"\x00", b"").strip() or b"<html/>"

    parser = parser_cls(recover=True, encoding=encoding, huge_tree=huge_tree)
    root = None
    try:
        root = etree.fromstring(body, parser=parser, base_url=base_url)
    except etree.XMLSyntaxError:
        if text or not _has_encoding_error(parser):
            raise
    if not text and _has_encoding_error(parser):
        # Invalid bytes reach the tree as is, and reading them raises
        # UnicodeDecodeError from lxml.
        return _root_from_decoded_body(body, parser_cls, base_url, huge_tree, encoding)
    if not huge_tree:
        for error in parser.error_log:
            if "use XML_PARSE_HUGE option" in error.message:
                warnings.warn(
                    "Input data is too big. Set huge_tree=True for huge_tree support.",
                    stacklevel=2,
                )
    if root is None:
        root = etree.fromstring(b"<html/>", parser=parser, base_url=base_url)
    return root
```

[parsel/selector.py](https://github.com/scrapy/parsel/blob/8a3f0412868d65626364db66a84f32fda15776b2/parsel/selector.py#L122-L163) · [More projects using lxml →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20that%20use%20lxml&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from lxml import etree
root = etree.fromstring(b'<message>Hello</message>')
print(root.text)

```

From [tutorial.html](https://lxml.de/tutorial.html)

### Beautiful Soup

[PyPI](https://pypi.org/project/beautifulsoup4) · [Docs](https://pypi.org/project/beautifulsoup4/)

Navigates, searches, and modifies XML or HTML parse trees.

- Downloads / mo: 320.8M
- Last release: 4.15.0
- License: MIT
- Capabilities: [From the Beautiful Soup docs](https://pypi.org/project/beautifulsoup4/)

**Strengths**

- **Navigates XML with CSS selectors.** Select namespaced XML elements with familiar CSS selector syntax.
- **Uses one markup-navigation interface.** Search and modify parse trees through the same Beautiful Soup interface.

**Watch out for**

- **XML parsing requires lxml.** Install lxml and request the XML parser explicitly for XML input.

```sh
pip install beautifulsoup4 lxml
```

**langchain-ai/langchain-community** (285 stars)

[langchain-ai/langchain-community](https://github.com/langchain-ai/langchain-community) 

```python
def parse_sitemap(self, soup: Any, *, depth: int = 0) -> List[dict]:
    """Parse sitemap xml and load into a list of dicts.

    Args:
        soup: BeautifulSoup object.
        depth: current depth of the sitemap. Default: 0

    Returns:
        List of dicts.
    """
    if depth >= self.max_depth:
        return []

    els: List[Dict] = []

    for url in soup.find_all("url"):
        loc = url.find("loc")
        if not loc:
            continue

        # Strip leading and trailing whitespace and newlines
        loc_text = loc.text.strip()

        if self.restrict_to_same_domain and not self.is_local:
            if _extract_scheme_and_domain(loc_text) != _extract_scheme_and_domain(
                self.web_path
            ):
                continue

        if self.allow_url_patterns and not any(
            re.match(regexp_pattern, loc_text)
            for regexp_pattern in self.allow_url_patterns
        ):
            continue

        els.append(
            {
                tag: prop.text.strip()
                for tag in ["loc", "lastmod", "changefreq", "priority"]
                if (prop := url.find(tag))
            }
        )

    for sitemap in soup.find_all("sitemap"):
        loc = sitemap.find("loc")
        if not loc:
            continue

        soup_child = self.scrape_all([loc.text], "xml")[0]
        els.extend(self.parse_sitemap(soup_child, depth=depth + 1))
    return els
```

[libs/community/langchain_community/document_loaders/sitemap.py](https://github.com/langchain-ai/langchain-community/blob/f425a3ed1933173fb3694b81359d1519c4f82d36/libs/community/langchain_community/document_loaders/sitemap.py#L151-L201) · [More projects using Beautiful Soup →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20that%20use%20beautifulsoup4&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from bs4 import BeautifulSoup
soup = BeautifulSoup('<message>Hello</message>', 'xml')
print(soup.message.get_text())

```

From [doc.md](https://www.crummy.com/software/BeautifulSoup/bs4/doc/)

### defusedxml

[GitHub](https://github.com/tiran/defusedxml) · [PyPI](https://pypi.org/project/defusedxml) · [Docs](https://pypi.org/project/defusedxml/)

Provides protected XML parsing functions compatible with standard-library parser objects.

- Downloads / mo: 276.9M
- Stars: 559
- Last release: 0.7.1
- License: PSF-2.0
- Capabilities: [From the defusedxml docs](https://pypi.org/project/defusedxml/)

**Strengths**

- **Blocks entity declarations by default.** The default parser settings reject declared entities and external references.
- **Keeps standard-library object compatibility.** Use returned parser objects with compatible standard-library XML APIs.

**Watch out for**

- **Writing XML uses standard-library APIs.** Use standard-library serializers for tree creation and XML output.
- **DTD rejection needs explicit configuration.** Set forbid_dtd=True when documents containing any DTD must be rejected.

```sh
pip install defusedxml
```

**microsoft/markitdown** (196.6K stars)

[microsoft/markitdown](https://github.com/microsoft/markitdown) 

```python
def convert(
    self,
    file_stream: BinaryIO,
    stream_info: StreamInfo,
    **kwargs: Any,  # Options to pass to the converter
) -> DocumentConverterResult:
    with zipfile.ZipFile(file_stream, "r") as z:
        # Extracts metadata (title, authors, language, publisher, date, description, cover) from an EPUB file.

        # Locate content.opf
        container_dom = minidom.parse(z.open("META-INF/container.xml"))
        opf_path = container_dom.getElementsByTagName("rootfile")[0].getAttribute(
            "full-path"
        )

        # Parse content.opf
        opf_dom = minidom.parse(z.open(opf_path))
        metadata: Dict[str, Any] = {
            "title": self._get_text_from_node(opf_dom, "dc:title"),
            "authors": self._get_all_texts_from_nodes(opf_dom, "dc:creator"),
            "language": self._get_text_from_node(opf_dom, "dc:language"),
            "publisher": self._get_text_from_node(opf_dom, "dc:publisher"),
            "date": self._get_text_from_node(opf_dom, "dc:date"),
            "description": self._get_text_from_node(opf_dom, "dc:description"),
            "identifier": self._get_text_from_node(opf_dom, "dc:identifier"),
        }

        # Extract manifest items (ID → href mapping)
        manifest = {
            item.getAttribute("id"): item.getAttribute("href")
            for item in opf_dom.getElementsByTagName("item")
        }

        # Extract spine order (ID refs)
        spine_items = opf_dom.getElementsByTagName("itemref")
        spine_order = [item.getAttribute("idref") for item in spine_items]

        # Convert spine order to actual file paths
        base_path = "/".join(
            opf_path.split("/")[:-1]
        )  # Get base directory of content.opf
        zip_names = set(z.namelist())
        spine = [
            self._resolve_manifest_href(manifest[item_id], base_path, zip_names)
            for item_id in spine_order
            if item_id in manifest
        ]

        # Extract and convert the content
        markdown_content: List[str] = []
        for file in spine:
            if file in z.namelist():
                with z.open(file) as f:
                    filename = os.path.basename(file)
                    extension = os.path.splitext(filename)[1].lower()
                    mimetype = MIME_TYPE_MAPPING.get(extension)
                    converted_content = self._html_converter.convert(
                        f,
                        StreamInfo(
                            mimetype=mimetype,
                            extension=extension,
                            filename=filename,
                        ),
                        **kwargs,
                    )
                    markdown_content.append(converted_content.markdown.strip())

        # Format and add the metadata
        metadata_markdown = []
        for key, value in metadata.items():
            if isinstance(value, list):
                value = ", ".join(value)
            if value:
                metadata_markdown.append(f"**{key.capitalize()}:** {value}")

        markdown_content.insert(0, "\n".join(metadata_markdown))

        return DocumentConverterResult(
            markdown="\n\n".join(markdown_content), title=metadata["title"]
        )
```

[packages/markitdown/src/markitdown/converters/_epub_converter.py](https://github.com/microsoft/markitdown/blob/ed178952a6672abdfd35b5f9e76a80b6cefc086e/packages/markitdown/src/markitdown/converters/_epub_converter.py#L55-L134) · [More projects using defusedxml →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20that%20use%20defusedxml&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from defusedxml.ElementTree import fromstring
root = fromstring('<message>Hello</message>')
print(root.text)

```

From [README.md](https://pypi.org/pypi/defusedxml/0.7.1/json#info.description)

### xmltodict

[GitHub](https://github.com/martinblech/xmltodict) · [PyPI](https://pypi.org/project/xmltodict) · [Docs](https://pypi.org/project/xmltodict/)

Converts XML documents to dictionaries and writes dictionaries as XML.

- Downloads / mo: 116.3M
- Stars: 5.8K
- Last release: 1.0.4
- License: MIT
- Capabilities: [From the xmltodict docs](https://pypi.org/project/xmltodict/)

**Strengths**

- **Writes dictionaries back as XML.** Use unparse to generate XML from a Python dictionary.
- **Streams records through callbacks.** Process records with item_depth and item_callback for large XML inputs.

**Watch out for**

- **Round-trips can change document structure.** Mixed content order, attribute order, and comment placement are not fully preserved.
- **Namespaces need explicit processing.** Enable process_namespaces when namespace URIs must be expanded.

```sh
pip install xmltodict
```

**getmoto/moto** (8.8K stars)

[getmoto/moto](https://github.com/getmoto/moto) 

```python
def _bucket_tagging_from_body(self) -> dict[str, str]:
    parsed_xml = xmltodict.parse(self.body)

    tags = {}
    # Optional if no tags are being sent:
    if parsed_xml["Tagging"].get("TagSet"):
        # If there is only 1 tag, then it's not a list:
        if not isinstance(parsed_xml["Tagging"]["TagSet"]["Tag"], list):
            tags[parsed_xml["Tagging"]["TagSet"]["Tag"]["Key"]] = parsed_xml[
                "Tagging"
            ]["TagSet"]["Tag"]["Value"]
        else:
            for tag in parsed_xml["Tagging"]["TagSet"]["Tag"]:
                if tag["Key"] in tags:
                    raise DuplicateTagKeys()
                tags[tag["Key"]] = tag["Value"]

    # Verify that "aws:" is not in the tags. If so, then this is a problem:
    for key, _ in tags.items():
        if key.startswith("aws:"):
            raise NoSystemTags()

    return tags
```

[moto/s3/responses.py](https://github.com/getmoto/moto/blob/ecc384b3e75ab471572d0d8d61c53cfd951c0fbc/moto/s3/responses.py#L2915-L2937) · [More projects using xmltodict →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20that%20use%20xmltodict&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import xmltodict
data = xmltodict.parse('<message>Hello</message>')
print(data['message'])

```

From [README.md](https://raw.githubusercontent.com/martinblech/xmltodict/master/README.md)

### xmlschema

[GitHub](https://github.com/sissaschool/xmlschema) · [PyPI](https://pypi.org/project/xmlschema) · [Docs](https://pypi.org/project/xmlschema/)

Validates and decodes XML Schema documents.

- Downloads / mo: 7.6M
- Stars: 475
- Last release: 4.3.2
- License: MIT
- Capabilities: [From the xmlschema docs](https://pypi.org/project/xmlschema/)

```sh
pip install xmlschema
```

**projectacrn/acrn-hypervisor** (1.3K stars)

[projectacrn/acrn-hypervisor](https://github.com/projectacrn/acrn-hypervisor) 

```python
def validate_scenario_schema(scenario_info):
    """
    Validate settings in scenario xml if there is scenario schema
    :param xsd_doc: scenario schema
    :param scenario_info: scenario file
    """

    """
    XMLSchema does not process XInclude.
    Use lxml to expand the schema which is feed to XMLSchema as a string.
    """
    xsd_doc = parse(acrn_config_utilities.SCENARIO_SCHEMA_FILE)
    xsd_doc.xinclude()
    my_schema = xmlschema.XMLSchema11(tostring(xsd_doc, encoding="unicode"))

    it = my_schema.iter_errors(scenario_info)
    for idx, validation_error in enumerate(it, start=1):
        key = ""
        if not validation_error:
            continue
        else:
            path = str(validation_error.path).split("/")
            cnt = 0
            for p in path:
                if '[' in p:
                    idx = int(p.split("[")[1].split("]")[0]) - 1
                    p = p.split("[")[0] + ":id=" + str(idx)
                    path[cnt] = p
                cnt = cnt + 1
            key =','.join(path[2:])
            element = "'" + path[-1] + "' "
            reason = validation_error.reason + ": last call: " + str(validation_error.obj)
            scenario_cfg_lib.ERR_LIST[key] = element + reason

```

[misc/config_tools/scenario_config/scenario_cfg_gen.py](https://github.com/projectacrn/acrn-hypervisor/blob/37b1c13f95696ddf543d6d77e4aed5641692672e/misc/config_tools/scenario_config/scenario_cfg_gen.py#L92-L124) · [More projects using xmlschema →](https://dashboard.exa.ai/playground/search?q=xmlschema%20GitHub%20projects)

**Quickstart**

```python
import xmlschema
schema = xmlschema.XMLSchema('<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"><xs:element name="message" type="xs:string"/></xs:schema>')
schema.validate('<message>Hello</message>')

```

From [usage.html](https://xmlschema.readthedocs.io/en/stable/usage.html)

### xsdata

[GitHub](https://github.com/tefra/xsdata) · [PyPI](https://pypi.org/project/xsdata) · [Docs](https://xsdata.readthedocs.io/)

Provides XML data binding for Python.

- Downloads / mo: 3.6M
- Stars: 457
- Last release: 26.10
- License: MIT
- Capabilities: [From the xsdata docs](https://xsdata.readthedocs.io/)

```sh
pip install xsdata
```

**MatthiasValvekens/pyHanko** (802 stars)

[MatthiasValvekens/pyHanko](https://github.com/MatthiasValvekens/pyHanko) 

```python
def generate_report(
    embedded_sig: EmbeddedPdfSignature, status: AdESBasicValidationResult
) -> str:
    """
    Generate signature validation report in XML format according to
    ETSI TS 119 102-2.

    :param embedded_sig:
        PDF signature to report on.
    :param status:
        AdES validation result to turn into a report.
    :return:
        A string representation of the validation report.
    """
    report = ts_11910202.ValidationReport(
        signature_validation_report=(_generate_report(embedded_sig, status),),
        signature_validation_objects=ts_11910202.ValidationObjectListType(
            tuple(
                _package_validation_object(vo)
                for vo in status.validation_objects
            )
        ),
    )
    from xsdata.formats.dataclass.serializers import XmlSerializer
    from xsdata.formats.dataclass.serializers.config import SerializerConfig

    config = SerializerConfig(indent="  ")
    ser = XmlSerializer(config=config).render(report, ns_map=NAMESPACES)
    return ser

```

[pkgs/pyhanko/src/pyhanko/sign/validation/report/tools.py](https://github.com/MatthiasValvekens/pyHanko/blob/f5666fe8a7195413463724de60bb0a2553cfeaf7/pkgs/pyhanko/src/pyhanko/sign/validation/report/tools.py#L390-L418) · [More projects using xsdata →](https://dashboard.exa.ai/playground/search?q=xsdata%20GitHub%20projects)

**Quickstart**

```python
from dataclasses import dataclass, field
from xsdata.formats.dataclass.parsers import XmlParser

@dataclass
class Message:
    class Meta:
        name = "message"
    text: str = field(default="", metadata={"type": "Text"})

message = XmlParser().from_string("<message>Hello</message>", Message)
print(message.text)

```

From [README.md](https://xsdata.readthedocs.io/en/latest/data_binding/basics/)

### pydantic-xml

[GitHub](https://github.com/dapper91/pydantic-xml) · [PyPI](https://pypi.org/project/pydantic-xml) · [Docs](https://pydantic-xml.readthedocs.io)

Extends Pydantic with XML support.

- Downloads / mo: 3.1M
- Stars: 257
- Last release: 2.22.0
- License: Unlicense
- Capabilities: [From the pydantic-xml docs](https://pydantic-xml.readthedocs.io)

```sh
pip install pydantic-xml
```

**protectai/vulnhuntr** (2.8K stars)

[protectai/vulnhuntr](https://github.com/protectai/vulnhuntr) 

```python
def run():
    parser = argparse.ArgumentParser(description='Analyze a GitHub project for vulnerabilities. Export your ANTHROPIC_API_KEY/OPENAI_API_KEY before running.')
    parser.add_argument('-r', '--root', type=str, required=True, help='Path to the root directory of the project')
    parser.add_argument('-a', '--analyze', type=str, help='Specific path or file within the project to analyze')
    parser.add_argument('-l', '--llm', type=str, choices=['claude', 'gpt', 'ollama'], default='claude', help='LLM client to use (default: claude)')
    parser.add_argument('-v', '--verbosity', action='count', default=0, help='Increase output verbosity (-v for INFO, -vv for DEBUG)')
    args = parser.parse_args()

    repo = RepoOps(args.root)
    code_extractor = SymbolExtractor(args.root)
    # Get repo files that don't include stuff like tests and documentation
    files = repo.get_relevant_py_files()

    # User specified --analyze flag
    if args.analyze:
        # Determine the path to analyze
        analyze_path = Path(args.analyze)

        # If the path is absolute, use it as is, otherwise join it with the root path so user can specify relative paths
        if analyze_path.is_absolute():
            files_to_analyze = repo.get_files_to_analyze(analyze_path)
        else:
            files_to_analyze = repo.get_files_to_analyze(Path(args.root) / analyze_path)

    # Analyze the entire project for network-related files
    else:
        files_to_analyze = repo.get_network_related_files(files)
    
    llm = initialize_llm(args.llm)

    readme_content = repo.get_readme_content()
    if readme_content:
        log.info("Summarizing project README")
        summary = llm.chat(
            (ReadmeContent(content=readme_content).to_xml() + b'\n' +
            Instructions(instructions=README_SUMMARY_PROMPT_TEMPLATE).to_xml()
            ).decode()
        )
        summary = extract_between_tags("summary", summary)[0]
        log.info("README summary complete", summary=summary)
    else:
        log.warning("No README summary found")
        summary = ''
    
    # Initialize the system prompt with the README summary
    system_prompt = (Instructions(instructions=SYS_PROMPT_TEMPLATE).to_xml() + b'\n' +
                ReadmeSummary(readme_summary=summary).to_xml()
                ).decode()
    
    llm = initialize_llm(args.llm, system_prompt)

    # files_to_analyze is either a list of all network-related files or a list containing a single file/dir to analyze
    for py_f in files_to_analyze:
        log.info(f"Performing initial analysis", file=str(py_f))

        # This is the Initial analysis
        with py_f.open(encoding='utf-8') as f:
            content = f.read()
            if not len(content):
                continue

            print(f"\nAnalyzing {py_f}")
            print('-' * 40 +'\n')

            user_prompt =(
                    FileCode(file_path=str(py_f), file_source=content).to_xml() + b'\n' +
                    Instructions(instructions=INITIAL_ANALYSIS_PROMPT_TEMPLATE).to_xml() + b'\n' +
                    AnalysisApproach(analysis_approach=ANALYSIS_APPROACH_TEMPLATE).to_xml() + b'\n' +
                    PreviousAnalysis(previous_analysis='').to_xml() + b'\n' +
                    Guidelines(guidelines=GUIDELINES_TEMPLATE).to_xml() + b'\n' +
                    ResponseFormat(response_format=json.dumps(Response.model_json_schema(), indent=4
                    )
                ).to_xml()
            ).decode()

            initial_analysis_report: Response = llm.chat(user_prompt, response_model=Response)
            log.info("Initial analysis complete", report=initial_analysis_report.model_dump())

            print_readable(initial_analysis_report)

            # Secondary analysis
            if initial_analysis_report.confidence_score > 0 and len(initial_analysis_report.vulnerability_types):

                for vuln_type in initial_analysis_report.vulnerability_types:

                    # Do not fetch the context code on the first pass of the secondary analysis because the context will be from the general analysis
                    stored_code_definitions = {}
                    definitions = CodeDefinitions(definitions=[])
                    same_context = False

                    # Don't include the initial analysis or the first iteration of the secondary analysis in the user_prompt
                    previous_analysis = ''
                    previous_context_amount = 0

                    for i in range(7):
                        log.info(f"Performing vuln-specific analysis", iteration=i, vuln_type=vuln_type, file=py_f)

                        # Only lookup context code and previous analysis on second pass and onwards
                        if i > 0:
                            previous_context_amount = len(stored_code_definitions)
                            previous_analysis = secondary_analysis_report.analysis

                            for context_item in secondary_analysis_report.context_code:
                                # Make sure bot isn't requesting the same code multiple times
                                if context_item.name not in stored_code_definitions:
                                    name = context_item.name
                                    code_line = context_item.code_line
                                    match = code_extractor.extract(name, code_line, files)
                                    if match:
                                        stored_code_definitions[name] = match

                            code_definitions = list(stored_code_definitions.values())
                            definitions = CodeDefinitions(definitions=code_definitions)
                            
                            if args.verbosity > 1:
                                for definition in definitions.definitions:
                                    if '\n' in definition.source:
                                        lines = definition.source.split('\n')
                                        snippet = lines[0] + '\n' + lines[1]
                                    else:
                                        snippet = definition.source[:75]
                                    
                                    print(f"Name: {definition.name}")
                                    print(f"Context search: {definition.context_name_requested}")
                                    print(f"File Path: {definition.file_path}")
                                    print(f"First two lines from source: {snippet}\n")

                        vuln_specific_user_prompt = (
                            FileCode(file_path=str(py_f), file_source=content).to_xml() + b'\n' +
                            definitions.to_xml() + b'\n' +  # These are all the requested context functions and classes
                            ExampleBypasses(
                                example_bypasses='\n'.join(VULN_SPECIFIC_BYPASSES_AND_PROMPTS[vuln_type]['bypasses'])
                            ).to_xml() + b'\n' +
                            Instructions(instructions=VULN_SPECIFIC_BYPASSES_AND_PROMPTS[vuln_type]['prompt']).to_xml() + b'\n' +
                            AnalysisApproach(analysis_approach=ANALYSIS_APPROACH_TEMPLATE).to_xml() + b'\n' +
                            PreviousAnalysis(previous_analysis=previous_analysis).to_xml() + b'\n' +
                            Guidelines(guidelines=GUIDELINES_TEMPLATE).to_xml() + b'\n' +
                            ResponseFormat(
                                response_format=json.dumps(
                                    Response.model_json_schema(), indent=4
                                )
                            ).to_xml()
                        ).decode()

                        secondary_analysis_report: Response = llm.chat(vuln_specific_user_prompt, response_model=Response)
                        log.info("Secondary analysis complete", secondary_analysis_report=secondary_analysis_report.model_dump())

                        if args.verbosity > 0:
                            print_readable(secondary_analysis_report)

                        if not len(secondary_analysis_report.context_code):
                            log.debug("No new context functions or classes found")
                            if args.verbosity == 0:
                                print_readable(secondary_analysis_report)
                            break
                        
                        # Check if any new context code is requested
                        if previous_context_amount >= len(stored_code_definitions) and i > 0:
                            # Let it request the same context once, then on the second time it requests the same context, break
                            if same_context:
                                log.debug("No new context functions or classes requested")
                                if args.verbosity == 0:
                                    print_readable(secondary_analysis_report)
                                break
                            same_context = True
                            log.debug("No new context functions or classes requested")
                    pass

```

[vulnhuntr/__main__.py](https://github.com/protectai/vulnhuntr/blob/ead88c5adba4279dae5c56d65124c530a9a1c5ae/vulnhuntr/__main__.py#L320-L486) · [More projects using pydantic-xml →](https://dashboard.exa.ai/playground/search?q=pydantic-xml%20GitHub%20projects)

**Quickstart**

```python
from pydantic_xml import BaseXmlModel, element

class Message(BaseXmlModel, tag="message"):
    text: str = element()

message = Message.from_xml(b"<message><text>Hello</text></message>")
print(message.text)

```

From [quickstart.html](https://pydantic-xml.readthedocs.io/en/latest/pages/quickstart.html)

### untangle

[GitHub](https://github.com/stchris/untangle) · [PyPI](https://pypi.org/project/untangle) · [Docs](https://pypi.org/project/untangle/)

Converts XML to Python objects

- Downloads / mo: 321.6K
- Stars: 628
- Last release: 1.3.0
- License: MIT
- Capabilities: [From the untangle docs](https://pypi.org/project/untangle/)

```sh
pip install untangle
```

**cloudbase/cloudbase-init** (544 stars)

[cloudbase/cloudbase-init](https://github.com/cloudbase/cloudbase-init) 

```python
def _wire_server_request(self, path, data_xml=None, headers=None,
                         parse_xml=True):
    if not self._base_url:
        raise exception.CloudbaseInitException(
            "Azure WireServer base url not set")

    all_headers = self._headers.copy()
    if data_xml:
        all_headers["Content-Type"] = "text/xml; charset=utf-8"
    if headers:
        all_headers.update(headers)

    data = self._exec_with_retry(
        lambda: super(AzureService, self)._http_request(
            path, data_xml, headers=all_headers))

    if parse_xml:
        return untangle.parse(io.StringIO(encoding.get_as_string(data)))
    else:
        return data
```

[cloudbaseinit/metadata/services/azureservice.py](https://github.com/cloudbase/cloudbase-init/blob/49a8c87549df935140982455c916125a9574c077/cloudbaseinit/metadata/services/azureservice.py#L101-L120) · [More projects using untangle →](https://dashboard.exa.ai/playground/search?q=untangle%20GitHub%20projects)

**Quickstart**

```python
import untangle
message = untangle.parse('<message>Hello</message>')
print(message.message.cdata)

```

From [README.md](https://github.com/stchris/untangle/blob/d389e335e5f9a0d47784f5b71afe4ecbc0e4baf3/README.md)

## FAQ

### Which Python XML library should I use?

[lxml](#lxml) suits building, editing, and parsing XML trees with the ElementTree API. [defusedxml](#defusedxml) suits untrusted XML that may declare entities. [xmltodict](#xmltodict) suits code that works with XML as Python dictionaries.

### What is lxml?

[lxml](#lxml) parses, edits, and serializes XML trees with the ElementTree API. It also parses large inputs incrementally.

### What is xmltodict?

[xmltodict](#xmltodict) converts XML documents to dictionaries and writes dictionaries back as XML. Round-trips may not preserve mixed content order, attribute order, or comment placement.

### How do I parse untrusted XML safely in Python?

[defusedxml](#defusedxml) provides protected parsing functions that reject declared entities and external references by default.

### lxml vs Beautiful Soup: which should I use for XML?

[lxml](#lxml) builds and edits XML trees directly. [Beautiful Soup](#beautiful-soup) navigates XML with CSS selectors and needs lxml as its XML parser.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Python XML libraries lxml xmltodict defusedxml Beautiful Soup parse namespaces streaming XML code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
