Skip to content

# `` xmlwriter

Classes:

- `XMLWriter` –

  A simple XML writer that writes to a stream.

## `` ESCAPE_ENTITIES `module-attribute`

    ESCAPE_ENTITIES = {'\r': '&#13;'}

## `` __all__ `module-attribute`

    __all__ = ['XMLWriter']

## `` XMLWriter

    XMLWriter(stream: IO[bytes], namespace_manager: NamespaceManager, encoding: Optional[str] = None, decl: int = 1, extra_ns: Optional[Dict[str, Namespace]] = None)

A simple XML writer that writes to a stream.

Methods:

- `attribute` –
- `element` –

  Utility method for adding a complete simple element

- `namespaces` –
- `pop` –
- `push` –
- `qname` –

  Compute qname for a uri using our extra namespaces,

- `text` –

Attributes:

- `closed` –
- `element_stack` (`List[str]`) –
- `extra_ns` –
- `indent` –
- `nm` –
- `stream` –

Source code in `rdflib/plugins/serializers/xmlwriter.py`

    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40

    def __init__(
        self,
        stream: IO[bytes],
        namespace_manager: NamespaceManager,
        encoding: Optional[str] = None,
        decl: int = 1,
        extra_ns: Optional[Dict[str, Namespace]] = None,
    ):
        encoding = encoding or "utf-8"
        encoder, decoder, stream_reader, stream_writer = codecs.lookup(encoding)
        # NOTE on type ignores: this is mainly because the variable is being re-used.
        # type error: Incompatible types in assignment (expression has type "StreamWriter", variable has type "IO[bytes]")
        self.stream = stream = stream_writer(stream)  # type: ignore[assignment]
        if decl:
            # type error: No overload variant of "write" of "IO" matches argument type "str"
            stream.write('<?xml version="1.0" encoding="%s"?>' % encoding)  # type: ignore[call-overload]
        self.element_stack: List[str] = []
        self.nm = namespace_manager
        self.extra_ns = extra_ns or {}
        self.closed = True

### `` closed `instance-attribute`

    closed = True

### `` element_stack `instance-attribute`

    element_stack: List[str] = []

### `` extra_ns `instance-attribute`

    extra_ns = extra_ns or {}

### `` indent `class-attribute` `instance-attribute`

    indent = property(__get_indent)

### `` nm `instance-attribute`

    nm = namespace_manager

### `` stream `instance-attribute`

    stream = stream_writer(stream)

### `` __close_start_tag

    __close_start_tag() -> None

Source code in `rdflib/plugins/serializers/xmlwriter.py`

    47
    48
    49
    50

    def __close_start_tag(self) -> None:
        if not self.closed:  # TODO:
            self.closed = True
            self.stream.write(">")

### `` __get_indent

    __get_indent() -> str

Source code in `rdflib/plugins/serializers/xmlwriter.py`

    42
    43

    def __get_indent(self) -> str:
        return "  " * len(self.element_stack)

### `` attribute

    attribute(uri: str, value: str) -> None

Source code in `rdflib/plugins/serializers/xmlwriter.py`

    106
    107
    108

    def attribute(self, uri: str, value: str) -> None:
        write = self.stream.write
        write(" %s=%s" % (self.qname(uri), quoteattr(value)))

### `` element

    element(uri: str, content: str, attributes: Dict[URIRef, str] = {}) -> None

Utility method for adding a complete simple element

Source code in `rdflib/plugins/serializers/xmlwriter.py`

    77
    78
    79
    80
    81
    82
    83
    84
    85

    def element(
        self, uri: str, content: str, attributes: Dict[URIRef, str] = {}
    ) -> None:
        """Utility method for adding a complete simple element"""
        self.push(uri)
        for k, v in attributes.items():
            self.attribute(k, v)
        self.text(content)
        self.pop()

### `` namespaces

    namespaces(namespaces: Iterable[Tuple[str, str]] = None) -> None

Source code in `rdflib/plugins/serializers/xmlwriter.py`

     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104

    def namespaces(self, namespaces: Iterable[Tuple[str, str]] = None) -> None:
        if not namespaces:
            namespaces = self.nm.namespaces()

        write = self.stream.write
        write("\n")
        for prefix, namespace in namespaces:
            if prefix:
                write('  xmlns:%s="%s"\n' % (prefix, namespace))
            # Allow user-provided namespace bindings to prevail
            elif prefix not in self.extra_ns:
                write('  xmlns="%s"\n' % namespace)

        for prefix, namespace in self.extra_ns.items():
            if prefix:
                write('  xmlns:%s="%s"\n' % (prefix, namespace))
            else:
                write('  xmlns="%s"\n' % namespace)

### `` pop

    pop(uri: Optional[str] = None) -> None

Source code in `rdflib/plugins/serializers/xmlwriter.py`

    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75

    def pop(self, uri: Optional[str] = None) -> None:
        top = self.element_stack.pop()
        if uri:
            assert uri == top
        write = self.stream.write
        if not self.closed:
            self.closed = True
            write("/>")
        else:
            if self.parent:
                write("\n")
                write(self.indent)
            write("</%s>" % self.qname(top))
        self.parent = True

### `` push

    push(uri: str) -> None

Source code in `rdflib/plugins/serializers/xmlwriter.py`

    52
    53
    54
    55
    56
    57
    58
    59
    60

    def push(self, uri: str) -> None:
        self.__close_start_tag()
        write = self.stream.write
        write("\n")
        write(self.indent)
        write("<%s" % self.qname(uri))
        self.element_stack.append(uri)
        self.closed = False
        self.parent = False

### `` qname

    qname(uri: str) -> str

Compute qname for a uri using our extra namespaces, or the given namespace manager

Source code in `rdflib/plugins/serializers/xmlwriter.py`

    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130

    def qname(self, uri: str) -> str:
        """Compute qname for a uri using our extra namespaces,
        or the given namespace manager"""

        for pre, ns in self.extra_ns.items():
            if uri.startswith(ns):
                if pre != "":
                    return ":".join([pre, uri[len(ns) :]])
                else:
                    return uri[len(ns) :]

        return self.nm.qname_strict(uri)

### `` text

    text(text: str) -> None

Source code in `rdflib/plugins/serializers/xmlwriter.py`

    110
    111
    112
    113
    114
    115
    116
    117

    def text(self, text: str) -> None:
        self.__close_start_tag()
        if "<" in text and ">" in text and "]]>" not in text:
            self.stream.write("<![CDATA[")
            self.stream.write(text)
            self.stream.write("]]>")
        else:
            self.stream.write(escape(text, ESCAPE_ENTITIES))