Skip to content
pekrauPublic

About

Minimalist package for reading, writing, creating and editing an XML element tree.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

7 Commits

Folders and files

Repository files navigation

minixml

Minimalist package for reading, writing, creating and editing an XML element tree.

Software

There are no dependencies except for the standard Python library.

This code has been lovingly hand-crafted. No AI tools were used in its development.

License

MIT

Installation

pip install minixml

Usage

import minixml

# Create the root element.
svg = minixml.Element("svg", width=320, height=130, xmlns="http://www.w3.org/2000/svg")


# A new element can be created from a parent element.
# It is automatically appended to the parent as a child.
svg.create(
    "rect",
    width=300,
    height=100,
    x=10,
    y=10,
    style="fill:rgb(0,0,255);stroke-width:3;stroke:red",
)


# An element can also be created from scratch and subsequently appended.
t = minixml.Element("text", x=5, y=15, fill="red")
t.append("I love SVG!")
svg.append(t)


# Serialize the Element tree into XML code; the XML declaration is prepended.
xmlcode = minixml.unparse(svg, indent=2)


# Ensure that unparse and parse are symmetric functions.
assert svg == minixml.parse(xmlcode)


# Display the result.
print(xmlcode)

Produces:

<?xml version="1.0" encoding="utf-8"?>
<svg width="320" height="130" xmlns="http://www.w3.org/2000/svg">
  <rect width="300" height="100" x="10" y="10" style="fill:rgb(0,0,255);stroke-width:3;stroke:red"/>
  <text x="5" y="15" fill="red">I love SVG!</text>
</svg>

API

The minixml namespace contains the features most client software will need:

These are automatically imported into minixml from minixml.element and minixml.io, which modules in most cases will not have to be imported directly by client software.

The following was generated using pydoc-markdown https://github.com/NiklasRosenstein/pydoc-markdown

minixml

Minimalist package for reading, writing, creating and editing an XML element tree.

minixml.element

Class to represent an XML element.

An instance of Element has a tag, attributes, children and possibly a parent. An instance can be part of at most one element tree. All operations should be performed using the methods, which will maintain the integrity of the references between instances.

Element Objects

class Element()

XML element having a tag, attributes, parent (if any) and children (if any).

__init__

def __init__(tag: str, *children, **attributes)

The instance is initialized as a root element (i.e. it has no parent).

__str__

def __str__()

Return the string representation of the element's starting tag.

__getitem__

def __getitem__(key: [int, str])

If 'key' is int, get the key'th child. If 'key' is str, get the value of the attribute.

__setitem__

def __setitem__(key: [int, str], value)

If 'key' is int, set the key'th child. Convert value to str if not Element. If 'key' is str, set the value of the attribute.

__delitem__

def __delitem__(key: [int, str])

If 'key' is int, delete the key'th child. If 'key' is str, delete the attribute.

__contains__

def __contains__(key: [str, Element])

If 'key' is str, does this element have the given attribute? If 'key' is an Element instance, is it among the children?

__iter__

def __iter__()

Iterate over the children of this element.

__len__

def __len__()

Return the number of children of this element.

__eq__

def __eq__(other)

Are this element and the other equal, recursively? Ignores the parent.

__iadd__

def __iadd__(other: [str, Element])

Append the other element to the end of the list of children of this element.

tag

@property
def tag() -> str

Return the tag of this element; read-only.

parent

@property
def parent() -> [None, Element]

Return the parent, if any, of this element; read-only.

attributes

@property
def attributes() -> dict

Return the dictionary of the attributes; read only. This is a shallow copy of the dictionary in the instance. Changing it will therefore not affect the attributes in the instance.

children

@property
def children() -> list

Return the list of children; read only. This is a shallow copy of the list in the instance. Changing it will therefore not affect the list of children in the instance.

text

@property
def text() -> str

Return the text content of this element. All children that are non-blank texts are concatenated.

root

@property
def root() -> Element

Return the root element of this element. May be self.

depth

@property
def depth() -> int

Depth of hierarchy for this element; number of parent steps to root.

get

def get(key: str, default=None)

Get the value of the 'key' attribute, or return the default if not present.

set

def set(key: str, value) -> None

Set the value of the attribute in this element.

index

def index(other: [str, Element]) -> int

Return the slot number for 'other' among the children of this element. Checks for element equality, not identity. Raise IndexError if not present.

append

def append(other: [str, Element]) -> None

Append the other element to the end of the list of children of this element.

insert

def insert(i: int, other: [str, Element]) -> None

Insert 'other' at position 'i' in the list of children of this element.

replace

def replace(i: int, other: [str, Element]) -> [str, Element]

Replace the element at position 'i' in the list of children of this element with 'other'. The replaced element is returned.

pop

def pop(i: [int, None] = None) -> [str, Element]

Remove the element at position i (last if None) and return it.

free

def free() -> Element

Remove this element from its parent, if any. Return itself.

create

def create(tag: str, **attributes) -> Element

Create an element with the given tag and attributes, and append to the children of this element. Return the created element.

copy

def copy() -> Element

Make a copy of this element and its children (i.e. deepcopy). The returned copy element has no parent.

walk

def walk(test=None)

Walk over this element and all its Element children recursively, yielding those elements that match the given test function. If no test function given, yield all. NOTE: The test function must handle both Element instances and strings.

diff

def diff(other: Element)

Return the first difference between this element and the other, recursively. Ignores the parents of this element and the other. Return a tuple describing the difference, or None.

minixml.io

Parse XML code into an Element tree, and unparse an Element tree into XML code.

parse

def parse(content, element_class=Element)

Parse the given XML content (string). Return the root XML element.

read

def read(filepath_or_stream, element_class=Element)

Read and parse the file given by its path, or the open file object. Return the root Element.

unparse

def unparse(element, indent=0, decl='<?xml version="1.0" encoding="utf-8"?>')

Return the XML code for the element and its children as a string. 'indent' is the number of blanks to use for each indentation level. The 'decl' value is output first if it is a non-empty string.

write

def write(outfile,
          element,
          indent=0,
          decl='<?xml version="1.0" encoding="utf-8"?>')

Write the XML of the element and its children into the open file object. The 'decl' value is output first if it is a non-empty string.

ContentHandler Objects

class ContentHandler(xml.sax.ContentHandler)

Handle XML SAX parse events, turning them into an Element tree.

About

Minimalist package for reading, writing, creating and editing an XML element tree.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages