Repository: tefra/xsdata

Issue:
Errors lxmlserializer
Download https://data.ndovloket.nl/netex/wsf/NeTEx_WSF_WSF_20240415_20240415.xml.gz in /tmp.

Notice:
1. Pretty printing is not respected
2. All attributes are not placed on the objects anymore. `<OperationalContextRef></OperationalContextRef>` expected `<OperationalContextRef ref="..."/>`

```
from xsdata.formats.dataclass.context import XmlContext
from xsdata.formats.dataclass.parsers import XmlParser
from xsdata.formats.dataclass.parsers.config import ParserConfig
from xsdata.formats.dataclass.parsers.handlers import LxmlEventHandler, lxml

from xsdata.formats.dataclass.serializers import LxmlTreeSerializer
from xsdata.formats.dataclass.serializers.config import SerializerConfig

from netex import ServiceFrame

context = XmlContext()
config = ParserConfig(fail_on_unknown_properties=False)
parser = XmlParser(context=context, config=config, handler=LxmlEventHandler)

tree = lxml.etree.parse("/tmp/NeTEx_WSF_WSF_20240415_20240415.xml.gz")

service_frame: ServiceFrame

for element in tree.iterfind(".//{http://www.netex.org.uk/netex}ServiceFrame"):
    service_frame = parser.parse(element, ServiceFrame)


serializer_config = SerializerConfig(ignore_default_attributes=True)
serializer_config.pretty_print = True
serializer_config.ignore_default_attributes = True
lxml_serializer = LxmlTreeSerializer(context, serializer_config)

tree = lxml.etree.parse("/tmp/NeTEx_WSF_WSF_20240415_20240415.xml.gz")

element = tree.find(".//{http://www.netex.org.uk/netex}ServiceFrame")
element.getparent().replace(element, lxml_serializer.render(service_frame))

tree.write("/tmp/test.xml", pretty_print=True, strip_text=True)
```

Discussion:
sonarcloud[bot]: ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=tefra_xsdata&pullRequest=1025) **Quality Gate passed**  
Issues  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 New issues](https://sonarcloud.io/project/issues?id=tefra_xsdata&pullRequest=1025&resolved=false&inNewCodePeriod=true)  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/component_measures?id=tefra_xsdata&pullRequest=1025&metric=new_accepted_issues&view=list)

Measures  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=tefra_xsdata&pullRequest=1025&resolved=false&inNewCodePeriod=true)  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/no-data-16px.png '') No data about Coverage  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=tefra_xsdata&pullRequest=1025&metric=new_duplicated_lines_density&view=list)  
  
[See analysis details on SonarCloud](https://sonarcloud.io/dashboard?id=tefra_xsdata&pullRequest=1025)



Patch:
diff --git a/xsdata/formats/dataclass/serializers/tree/mixins.py b/xsdata/formats/dataclass/serializers/tree/mixins.py
index 665c430f..70e2d7c7 100644
--- a/xsdata/formats/dataclass/serializers/tree/mixins.py
+++ b/xsdata/formats/dataclass/serializers/tree/mixins.py
@@ -1,12 +1,11 @@
 import abc
 from dataclasses import dataclass
-from typing import Any, Dict, Optional, Protocol
+from typing import Any, Dict, Protocol
 
 from xsdata.exceptions import XmlHandlerError
 from xsdata.formats.converter import converter
 from xsdata.formats.dataclass.serializers.mixins import EventGenerator, XmlWriterEvent
 from xsdata.formats.types import T
-from xsdata.models.enums import EventType
 
 
 class TreeBuilder(Protocol):
@@ -39,8 +38,9 @@ class TreeSerializer(EventGenerator):
         """
         pending_tag = None
         pending_attrs: Dict[str, Any] = {}
+        flush_events = (XmlWriterEvent.START, XmlWriterEvent.END, XmlWriterEvent.DATA)
         for event, *element in self.generate(obj):
-            if pending_tag is not None:
+            if pending_tag is not None and event in flush_events:
                 builder.start(pending_tag, pending_attrs)
                 pending_tag = None
                 pending_attrs = {}
@@ -51,7 +51,7 @@ class TreeSerializer(EventGenerator):
             elif event == XmlWriterEvent.ATTR:
                 key, value = element
                 pending_attrs[key] = self.encode_data(value)
-            elif event == EventType.END:
+            elif event == XmlWriterEvent.END:
                 builder.end(*element)
             elif event == XmlWriterEvent.DATA:
                 data = self.encode_data(element[0])


Test patch:
diff --git a/tests/formats/dataclass/serializers/tree/test_lxml.py b/tests/formats/dataclass/serializers/tree/test_lxml.py
index 96a3e9c2..2d820e64 100644
--- a/tests/formats/dataclass/serializers/tree/test_lxml.py
+++ b/tests/formats/dataclass/serializers/tree/test_lxml.py
@@ -15,7 +15,7 @@ class LxmlTreeSerializerTests(TestCase):
         actual = etree.tostring(result)
         expected = (
             '<ns0:books xmlns:ns0="urn:books">\n'
-            "  <book>\n"
+            '  <book id="bk001" lang="en">\n'
             "    <author>Hightower, Kim</author>\n"
             "    <title>The First Book</title>\n"
             "    <genre>Fiction</genre>\n"
@@ -23,7 +23,7 @@ class LxmlTreeSerializerTests(TestCase):
             "    <pub_date>2000-10-01</pub_date>\n"
             "    <review>An amazing story of nothing.</review>\n"
             "  </book>\n"
-            "  <book>\n"
+            '  <book id="bk002" lang="en">\n'
             "    <author>Nagata, Suanne</author>\n"
             "    <title>Becoming Somebody</title>\n"
             "    <genre>Biography</genre>\n"
diff --git a/tests/formats/dataclass/serializers/tree/test_native.py b/tests/formats/dataclass/serializers/tree/test_native.py
index 0da3cdb8..5337bb6d 100644
--- a/tests/formats/dataclass/serializers/tree/test_native.py
+++ b/tests/formats/dataclass/serializers/tree/test_native.py
@@ -18,7 +18,7 @@ class XmlTreeSerializerTests(TestCase):
         actual = ElementTree.tostring(result)
         expected = (
             '<ns0:books xmlns:ns0="urn:books">\n'
-            "  <book>\n"
+            '  <book id="bk001" lang="en">\n'
             "    <author>Hightower, Kim</author>\n"
             "    <title>The First Book</title>\n"
             "    <genre>Fiction</genre>\n"
@@ -26,7 +26,7 @@ class XmlTreeSerializerTests(TestCase):
             "    <pub_date>2000-10-01</pub_date>\n"
             "    <review>An amazing story of nothing.</review>\n"
             "  </book>\n"
-            "  <book>\n"
+            '  <book id="bk002" lang="en">\n'
             "    <author>Nagata, Suanne</author>\n"
             "    <title>Becoming Somebody</title>\n"
             "    <genre>Biography</genre>\n"