Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
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
lxml has the most monthly downloads in this comparison, at 445.4M.
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
Beautiful Soup
Navigates, searches, and modifies XML or HTML parse trees.
Downloads / mo
320.8M
Last release
4.15.0
License
MIT
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.
Limitations
XML parsing requires lxml.Install lxml and request the XML parser explicitly for XML input.
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
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
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.
Limitations
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.
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
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
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)
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
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
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
FAQ
lxml suits building, editing, and parsing XML trees with the ElementTree API. defusedxml suits untrusted XML that may declare entities. xmltodict suits code that works with XML as Python dictionaries.
lxml parses, edits, and serializes XML trees with the ElementTree API. It also parses large inputs incrementally.
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.
defusedxml provides protected parsing functions that reject declared entities and external references by default.
lxml builds and edits XML trees directly. Beautiful Soup navigates XML with CSS selectors and needs lxml as its XML parser.
For coding agents
Found your XML library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.