"""Offline Eclipse New XML File wizard, DTD/XSD validation & Design/Source verifier for Ch13 (create-xml-file)."""
import io
import json
import xml.etree.ElementTree as ET
from lxml import etree
VERSION = "CPython 3.12.14 + lxml offline Eclipse XML-editor/schema verifier (desktop Eclipse SWT GUI absent)"
def check(name, summary, expected, actual):
return {
"name": name,
"summary": summary,
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def normalize_xml_filename(raw_name):
cleaned = raw_name.strip()
if not cleaned.lower().endswith(".xml"):
cleaned += ".xml"
return cleaned
def main():
cases = []
# Case 1: Ctrl+N wizard search filter ("XML") and .xml filename normalization
wizards = [
("Java", "Java Project"),
("Java", "Class"),
("XML", "XML File"),
("XML", "XML Schema File"),
("XML", "DTD File"),
]
matched_xml = [w for cat, w in wizards if "xml" in cat.lower() or "xml" in w.lower()]
cases.append(
check(
"wizard_filter_and_xml_filename_check",
"Verify Ctrl+N wizard search for 'XML' and automatic .xml filename extension normalization",
{
"matched_wizards": ["XML File", "XML Schema File", "DTD File"],
"normalized_from_stem": "config.xml",
"normalized_existing_ext": "beans.xml",
},
{
"matched_wizards": matched_xml,
"normalized_from_stem": normalize_xml_filename("config"),
"normalized_existing_ext": normalize_xml_filename("beans.xml"),
},
)
)
# Case 2: Well-formed XML generation & malformed XML error detection
xml_doc = '<?xml version="1.0" encoding="UTF-8"?>\n<appConfig><name>EclipseDemo</name><port>8080</port></appConfig>\n'
parsed = ET.fromstring(xml_doc)
malformed_caught = False
try:
ET.fromstring("<appConfig><name>Broken</appConfig>")
except ET.ParseError:
malformed_caught = True
cases.append(
check(
"xml_wellformed_generation_and_parse",
"Verify UTF-8 XML document parsing and detection of unclosed tag errors",
{"root_tag": "appConfig", "port": "8080", "malformed_caught": True},
{"root_tag": parsed.tag, "port": parsed.findtext("port"), "malformed_caught": malformed_caught},
)
)
# Case 3: DTD and XML Schema (XSD) validation via lxml.etree
dtd = etree.DTD(io.StringIO("<!ELEMENT note (to,body)><!ELEMENT to (#PCDATA)><!ELEMENT body (#PCDATA)>"))
good_dtd_doc = etree.fromstring(b"<note><to>Dev</to><body>Ready</body></note>")
bad_dtd_doc = etree.fromstring(b"<note><to>Dev</to></note>")
xsd_src = b"""<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="service">
<xs:complexType>
<xs:sequence>
<xs:element name="host" type="xs:string"/>
<xs:element name="port" type="xs:integer"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
"""
schema = etree.XMLSchema(etree.XML(xsd_src))
good_xsd_doc = etree.XML(b"<service><host>localhost</host><port>8080</port></service>")
bad_xsd_doc = etree.XML(b"<service><host>localhost</host><port>not-a-number</port></service>")
cases.append(
check(
"xml_dtd_and_xsd_schema_binding",
"Validate XML instances against both DTD and XML Schema (XSD) definitions",
{
"dtd_valid": True,
"dtd_invalid_rejected": True,
"xsd_valid": True,
"xsd_invalid_rejected": True,
},
{
"dtd_valid": dtd.validate(good_dtd_doc),
"dtd_invalid_rejected": not dtd.validate(bad_dtd_doc),
"xsd_valid": schema.validate(good_xsd_doc),
"xsd_invalid_rejected": not schema.validate(bad_xsd_doc),
},
)
)
# Case 4: XML Editor Design-tree vs Source-text round-trip equivalence
tree_model = {"tag": "projectMeta", "attrs": {"version": "1.0"}, "children": [{"tag": "author", "text": "mbsky"}]}
el = ET.Element(tree_model["tag"], tree_model["attrs"])
for child in tree_model["children"]:
c = ET.SubElement(el, child["tag"])
c.text = child["text"]
source_xml = ET.tostring(el, encoding="unicode")
reparsed = ET.fromstring(source_xml)
cases.append(
check(
"design_tree_vs_source_roundtrip",
"Verify bidirectional consistency between XML Editor Design tree and Source text views",
{"tag": "projectMeta", "version": "1.0", "author": "mbsky"},
{
"tag": reparsed.tag,
"version": reparsed.attrib["version"],
"author": reparsed.findtext("author"),
},
)
)
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/eclipse-create-xml-file-lab/explore-create-xml-file.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-create-xml-file.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联35章) · 含当前章节或实例 · mbskycom202612a2259.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2270.zip