Python XML DOM 实战应用案例解析 从基础到进阶的完整操作指南

引言:XML DOM 在现代开发中的地位
XML(可扩展标记语言)作为一种通用的数据交换格式,在企业级应用、配置文件、Web服务等领域仍然发挥着重要作用。DOM(Document Object Model)作为XML文档的标准解析接口,提供了一种树状结构来表示文档,使得开发者能够方便地遍历、修改和查询XML数据。
在Python中,标准库提供了
xml.dom
模块来处理XML文档。虽然相比
xml.etree.ElementTree
,DOM API可能显得稍微复杂,但它提供了更完整的W3C标准支持,特别是在需要处理命名空间、实体引用或进行复杂文档操作时表现出色。
第一部分:XML DOM 基础概念
1.1 XML DOM 核心概念
XML DOM将整个XML文档视为一个树状结构,每个元素、属性、文本节点都是树中的一个节点。理解以下核心概念至关重要:
Document
:DOM树的根节点,代表整个XML文档
Element
:XML元素节点,可以包含子节点和属性
Attribute
:元素的属性节点
Text
:元素内的文本内容
Comment
:注释节点
NodeList
:节点列表,用于存储多个节点
1.2 Python DOM 模块介绍
Python标准库中的
xml.dom
模块提供了DOM解析功能,主要包含:
minidom
:轻量级DOM实现,适合大多数场景
pulldom
:流式DOM解析,适合处理大文件
第二部分:基础操作实战
2.1 环境准备与安装
Python标准库已包含XML DOM支持,无需额外安装:
import xml.dom.minidom
from xml.dom.minidom import parse, parseString
2.2 解析XML文档
2.2.1 从文件解析XML
import xml.dom.minidom as minidom

# 准备示例XML文件内容
xml_content = “””


Everyday Italian
Giada De Laurentiis
2005 30.00


Harry Potter
J.K. Rowling
2005 29.99

“””

# 将字符串写入临时文件进行演示
with open(‘books.xml’, ‘w’, encoding=’utf-8′) as f:
f.write(xml_content)

# 使用minidom解析XML文件
dom = minidom.parse(‘books.xml’)
print(“XML文档解析成功!”)
print(f”文档根元素: {dom.documentElement.tagName}”)
2.2.2 从字符串解析XML
# 直接从字符串解析
dom = minidom.parseString(xml_content)
print(“字符串解析成功!”)
2.3 遍历DOM树
2.3.1 获取节点信息
def print_node_info(node, indent=0):
“””递归打印节点信息”””
prefix = ” ” * indent
node_type = node.nodeType

if node_type == node.ELEMENT_NODE:
print(f”{prefix}元素节点: <{node.tagName}>“)
# 打印属性
if node.hasAttributes():
for attr_name, attr_value in node.attributes.items():
print(f”{prefix} 属性: {attr_name} = {attr_value}”)
elif node_type == node.TEXT_NODE:
text = node.data.strip()
if text:
print(f”{prefix}文本节点: ‘{text}’”)
elif node_type == node.COMMENT_NODE:
print(f”{prefix}注释节点: {node.data}”)

# 递归处理子节点
for child in node.childNodes:
print_node_info(child, indent + 1)

# 使用示例
dom = minidom.parseString(xml_content)
print_node_info(dom.documentElement)
2.3.2 使用节点列表
# 获取所有book元素
dom = minidom.parseString(xml_content)
books = dom.getElementsByTagName(‘book’)
print(f”找到 {books.length} 本书”)

# 遍历每本书
for i, book in enumerate(books):
print(f”\n第 {i+1} 本书:”)
# 获取title元素
title = book.getElementsByTagName(‘title’)[0]
print(f” 标题: {title.firstChild.data}”)

# 获取作者
author = book.getElementsByTagName(‘author’)[0]
print(f” 作者: {autho
2.4 查找特定节点
2.4.1 getElementById 方法
# 注意:需要确保XML中有ID属性,且DTD定义了ID类型
xml_with_id = “””


Everyday Italian
Giada De Laurentiis
2005 30.00

“””

dom = minidom.parseString(xml_with_id)
# 如果XML有ID属性,可以通过getElementById获取
book = dom.getElementById(‘b1’)
if book:
print(f”找到ID为b1的元素: {book.tagName}”)
2.4.2 使用 getElementsByTagName
# 获取所有title元素
dom = minidom.parseString(xml_content)
titles = dom.getElementsByTagName(‘title’)

for title in titles:
# 获取父元素
book = title.parentNode
category = book.getAttribute(‘category’)
print(f”书籍分类: {category}, 标题: {title.firstChild.data}”)
2.5 创建和修改XML
2.5.1 创建新文档
def create_book_xml():
“””创建一个新的XML文档”””
# 创建DOM文档对象
impl = minidom.getDOMImplementation()
dom = impl.createDocument(None, ‘bookstore’, None)

# 获取根元素
root = dom.documentElement

# 创建第一个book元素
book1 = dom.createElement(‘book’)
book1.setAttribute(‘category’, ‘FICTION’)
root.appendChild(book1)

# 创建title元素
title = dom.createElement(‘title’)
title.setAttribute(‘lang’, ‘en’)
title_text = dom.createTextNode(‘The Great Gatsby’)
title.appendChild(title_text)
book1.appendChild(title)

# 创建author元素
author = dom.createElement(‘author’)
author_text = dom.createTextNode(‘F. Scott Fitzgerald’)
author.appendChild(author_text)
book1.appendChild(author)

# 创建year元素
year = dom.createElement(‘year’)
year_text = dom.createTextNode(‘1925’)
year.appendChild(year_text)
book1.appendChild(year)

# 创建price元素
price = dom.createElement(‘price’)
price_text = dom.createTextNode(‘12.99’)
price.appendChild(price_text)
book1.appendChild(price)

return dom

# 创建并保存
dom = create_book_xml()
with open(‘new_books.xml’, ‘w’, encoding=’utf-8′) as f:
dom.writexml(f, indent=’ ‘, addindent=’ ‘, newl=’\n’)
print(“新XML文档创建成功!”)
2.5.2 修改现有文档
# 修改现有XML
dom = minidom.parseString(xml_content)
books = dom.getElementsByTagName(‘book’)

# 修改第一本书的价格
first_book = books[0]
price_element = first_book.getElementsByTagName(‘price’)[0]
price_element.firstChild.data = ‘35.00’ # 修改价格

# 添加新属性
first_book.setAttribute(‘bestseller’, ‘true’)

# 添加新元素
discount = dom.createElement(‘discount’)
discount_text = dom.createTextNode(‘10%’)
discount.appendChild(discount_text)
first_book.appendChild(discount)

# 保存修改
with open(‘modified_books.xml’, ‘w’, encoding=’utf-8′) as f:
dom.writexml(f, indent=’ ‘, addindent=’ ‘, newl=’\n’)
print(“XML文档修改成功!”)
2.6 删除节点
# 删除节点示例
dom = minidom.parseString(xml_content)
books = dom.getElementsByTagName(‘book’)

# 删除第二本书
if books.length > 1:
second_book = books[1]
second_book.parentNode.removeChild(second_book)
print(“已删除第二本书”)

# 删除特定元素
first_book = books[0]
price_elements = first_book.getElementsByTagName(‘price’)
if price_elements.length > 0:
price_element = price_elements[0]
price_element.parentNode.removeChild(price_element)
print(“已删除价格元素”)

# 保存结果
with open(‘removed_books.xml’, ‘w’, encoding=’utf-8′) as f:
dom.writexml(f, indent=’ ‘, addindent=’ ‘, newl=’\n’)
第三部分:进阶操作与实战案例
3.1 处理XML命名空间
3.1.1 带命名空间的XML解析
# 带命名空间的XML示例
xml_ns = “””


Everyday Italian
Giada De Laurentiis
2005
30.00

“””

dom = minidom.parseString(xml_ns)

# 获取带命名空间的元素
books = dom.getElementsByTagNameNS(‘http://example.com/books’, ‘book’)
print(f”找到 {books.length} 本书(使用命名空间)”)

for book in books:
titles = book.getElementsByTagNameNS(‘http://example.com/books’, ‘title’)
if titles.length > 1:
title = titles[0]
print(f”标题: {title.firstChild.data}”)
3.1.2 创建带命名空间的元素
def create_namespaced_xml():
“””创建带命名空间的XML”””
impl = minidom.getDOMImplementation()
dom = impl.createDocument(‘http://example.com/books’, ‘ns:bookstore’, None)

root = dom.documentElement
root.setAttribute(‘xmlns:ns’, ‘http://example.com/books’)

# 创建带命名空间的元素
book = dom.createElementNS(‘http://example.com/books’, ‘ns:book’)
book.setAttribute(‘category’, ‘FICTION’)

title = dom.createElementNS(‘http://example.com/books’, ‘ns:title’)
title.setAttribute(‘lang’, ‘en’)
title_text = dom.createTextNode(‘The Great Gatsby’)
title.appendChild(title_text)
book.appendChild(title)

root.appendChild(book)

return dom

ns_dom = create_namespaced_xml()
with open(‘namespaced_books.xml’, ‘w’, encoding=’utf-8′) as f:
ns_dom.writexml(f, indent=’ ‘, addindent=’ ‘, newl=’\n’)
print(“带命名空间的XML创建成功!”)
3.2 处理实体引用
# XML实体引用示例
xml_with_entities = “””


]>


Python © Programming
Best book ™ for learning Python

“””

# 解析包含实体的XML
dom = minidom.parseString(xml_with_entities)
books = dom.getElementsByTagName(‘book’)

for book in books:
title = book.getElementsByTagName(‘title’)[0]
description = book.getElementsByTagName(‘description’)[0]
print(f”标题: {title.firstChild.data}”)
print(f”描述: {description.firstChild.data}”)
3.3 大型XML文件处理
3.3.1 使用 pulldom 处理大文件
import xml.dom.pulldom as pulldom

# 创建一个大型XML文件用于演示
def create_large_xml(filename, num_books=1000):
with open(filename, ‘w’, encoding=’utf-8′) as f:
f.write(‘\n’)
f.write(‘\n’)
for i in range(num_books):
f.write(f’ \n’)
f.write(f’ Book {i}\n’)
f.write(f’ Author {i % 10}\n’)
f.write(f’ {10 + i * 0.1:.2f}\n’)
f.write(f’
\n’)
f.write(‘
\n’)

# 使用pulldom处理大文件
def process_large_xml(filename):
“””使用pulldom流式处理大文件”””
event_stream = pulldom.parse(filename)
book_count = 0
expensive_books = []

for event, node in event_stream:
if event == pulldom.START_ELEMENT and node.tagName == ‘book’:
# 暂停流处理,展开当前节点
event_stream.expandNode(node)
price = node.getElementsByTagName(‘price’)[0].firstChild.data
if float(price) > 20.0:
title = node.getElementsByTagName(‘title’)[0].firstChild.data
expensive_books.append(title)
book_count += 1

print(f”找到 {book_count} 本价格超过20的书”)
return expensive_books

# 创建并处理大型XML
create_large_xml(‘large_books.xml’, 1000)
expensive_books = process_large_xml(‘large_books.xml’)
print(“部分高价书籍:”, expensive_books[:5])
3.4 XML与JSON转换
3.4.1 XML转JSON
import json

def xml_to_dict(node):
“””递归将XML节点转换为字典”””
if node.nodeType == node.TEXT_NODE:
return node.data.strip()

if node.nodeType != node.ELEMENT_NODE:
return None

result = {}

# 处理属性
if node.hasAttributes():
result[‘@attributes’] = {}
for i in range(node.attributes.length):
attr = node.attributes.item(i)
result[‘@attributes’][attr.name] = attr.value

# 处理子节点
children = []
text_content = []

for child in node.childNodes:
if child.nodeType == child.TEXT_NODE:
text = child.data.strip()
if text:
text_content.append(text)
else:
child_result = xml_to_dict(child)
if child_result is not None:
children.append((child.tagName, child_result))

# 如果有文本内容,直接返回
if text_content and not children:
return text_content[0] if len(text_content) == 1 else text_content

# 组织子节点
for tag_name, child_data in children:
if tag_name not in result:
result[tag_name] = child_data
else:
# 如果有多个同名节点,转换为列表
if not isinstance(result[tag_name], list):
result[tag_name] = [result[tag_name]]
result[tag_name].append(child_data)

return result

# 使用示例
dom = minidom.parseString(xml_content)
xml_dict = xml_to_dict(dom.documentElement)
json_str = json.dumps(xml_dict, indent=2, ensure_ascii=False)
print(“XML转JSON结果:”)
print(json_str)
3.4.2 JSON转XML
def dict_to_xml(parent, data, tag_name=None):
“””递归将字典转换为XML节点”””
if isinstance(data, dict):
# 处理属性
if ‘@attributes’ in data:
for attr_name, attr_value in data[‘@attributes’].items():
parent.setAttribute(attr_name, attr_value)
data = {k: v for k, v in data.items() if k != ‘@attributes’}

for key, value in data.items():
if isinstance(value, list):
for item in value:
dict_to_xml(parent, item, key)
else:
child = parent.ownerDocument.createElement(key)
parent.appendChild(child)
dict_to_xml(child, value, key)

elif isinstance(data, (str, int, float)):
if tag_name:
child = parent.ownerDocument.createElement(tag_name)
parent.appendChild(child)
text = parent.ownerDocument.createTextNode(str(data))
child.appendChild(text)
else:
text = parent.ownerDocument.createTextNode(str(data))
parent.appendChild(text)

# 使用示例
json_data = {
“bookstore”: {
“book”: [
{
“@attributes”: {“category”: “COOKING”},
“title”: {“@attributes”: {“lang”: “en”}, “#text”: “Everyday Italian”},
“author”: “Giada De Laurentiis”,
“year”: 2005,
“price”: 30.00
},
{
“@attributes”: {“category”: “CHILDREN”},
“title”: {“@attributes”: {“lang”: “en”}, “#text”: “Harry Potter”},
“author”: “J.K. Rowling”,
“year”: 2005,
“price”: 29.99
}
]
}
}

impl = minidom.getDOMImplementation()
dom = impl.createDocument(None, ‘root’, None)
root = dom.documentElement

dict_to_xml(root, json_data)
dom.documentElement = dom.documentElement.firstChild # 移除root包装

with open(‘from_json.xml’, ‘w’, encoding=’utf-8′) as f:
dom.writexml(f, indent=’ ‘, addindent=’ ‘, newl=’\n’)
print(“JSON转XML成功!”)
3.5 XML验证
3.5.1 使用DTD验证
# 创建带DTD的XML
xml_with_dtd = “””








]>


Everyday Italian
Giada De Laurentiis
2005 30.00

“””

# 验证XML(注意:minidom本身不提供验证功能,需要使用其他库如lxml)
# 这里展示如何检查基本结构
dom = minidom.parseString(xml_with_dtd)
books = dom.getElementsByTagName(‘book’)

for book in books:
required_elements = [‘title’, ‘author’, ‘year’, ‘price’]
missing = []
for elem in required_elements:
if book.getElementsByTagName(elem).length == 0:
missing.append(elem)

if missing:
print(f”警告: 书籍缺少元素: {missing}”)
else:
print(f”书籍结构完整: {book.getElementsByTagName(‘title’)[0].firstChild.data}”)
3.6 性能优化技巧
3.6.1 使用节点缓存
class XMLProcessor:
“””XML处理优化类”””
def __init__(self, dom):
self.dom = dom
self._cache = {}

def get_books_by_category(self, category):
“””缓存查询结果”””
cache_key = f”category_{category}”
if cache_key in self._cache:
return self._cache[cache_key]

books = []
all_books = self.dom.getElementsByTagName(‘book’)
for book in all_books:
if book.getAttribute(‘category’) == category:
books.append(book)

self._cache[cache_key] = books
return books

def get_book_price(self, book):
“””缓存价格计算”””
book_id = book.getAttribute(‘id’) if book.hasAttribute(‘id’) else None
if book_id:
cache_key = f”price_{book_id}”
if cache_key in self._cache:
return self._cache[cache_key]

price_elements = book.getElementsByTagName(‘price’)
if price_elements.length > 0:
price = float(price_elements[0].firstChild.data)
if book_id:
self._cache[cache_key] = price
return price
return None

# 使用示例
dom = minidom.parseString(xml_content)
processor = XMLProcessor(dom)

# 第一次查询
cooking_books = processor.get_books_by_category(‘COOKING’)
print(f”烹饪类书籍: {len(cooking_books)}”)

# 第二次查询(从缓存获取)
cooking_books_cached = processor.get_books_by_category(‘COOKING’)
print(f”烹饪类书籍(缓存): {len(cooking_books_cached)}”)
3.6.2 使用上下文管理器
from contextlib import contextmanager

@contextmanager
def xml_context(filename, mode=’r’):
“””XML文件处理上下文管理器”””
try:
if mode == ‘r’:
dom = minidom.parse(filename)
else:
impl = minidom.getDOMImplementation()
dom = impl.createDocument(None, ‘root’, None)
yield dom
finally:
# 清理工作
pass

# 使用上下文管理器
with xml_context(‘books.xml’) as dom:
books = dom.getElementsByTagName(‘book’)
print(f”找到 {books.length} 本书”)
第四部分:实战案例
4.1 案例1:配置文件管理器
class ConfigManager:
“””基于XML的配置文件管理器”””
def __init__(self, config_file):
self.config_file = config_file
self.dom = None
self.load_config()

def load_config(self):
“””加载配置文件”””
try:
self.dom = minidom.parse(self.config_file)
except FileNotFoundError:
# 创建默认配置
self.create_default_config()

def create_default_config(self):
“””创建默认配置”””
impl = minidom.getDOMImplementation()
self.dom = impl.createDocument(None, ‘configuration’, None)
root = self.dom.documentElement

# 添加数据库配置
db_config = self.dom.createElement(‘database’)
db_config.appendChild(self._create_element(‘host’, ‘localhost’))
db_config.appendChild(self._create_element(‘port’, ‘5432’))
db_config.appendChild(self._create_element(‘name’, ‘mydb’))
root.appendChild(db_config)

# 添加日志配置
log_config = self.dom.createElement(‘logging’)
log_config.appendChild(self._create_element(‘level’, ‘INFO’))
log_config.appendChild(self._create_element(‘file’, ‘app.log’))
root.appendChild(log_config)

self.save_config()

def _create_element(self, tag, text):
“””辅助方法:创建带文本的元素”””
elem = self.dom.createElement(tag)
text_node = self.dom.createTextNode(str(text))
elem.appendChild(text_node)
return elem

def get_db_config(self):
“””获取数据库配置”””
db_elem = self.dom.getElementsByTagName(‘database’)[0]
config = {}
for child in db_elem.childNodes:
if child.nodeType == child.ELEMENT_NODE:
config[child.tagName] = child.firstChild.data
return config

def set_db_config(self, **kwargs):
“””设置数据库配置”””
db_elem = self.dom.getElementsByTagName(‘database’)[0]
for key, value in kwargs.items():
elem = self.dom.getElementsByTagName(key)[0]
elem.firstChild.data = str(value)

def get_log_level(self):
“””获取日志级别”””
log_elem = self.dom.getElementsByTagName(‘logging’)[0]
level_elem = log_elem.getElementsByTagName(‘level’)[0]
return level_elem.firstChild.data

def set_log_level(self, level):
“””设置日志级别”””
log_elem = self.dom.getElementsByTagName(‘logging’)[0]
level_elem = log_elem.getElementsByTagName(‘level’)[0]
level_elem.firstChild.data = level

def save_config(self):
“””保存配置”””
with open(self.config_file, ‘w’, encoding=’utf-8′) as f:
self.dom.writexml(f, indent=’ ‘, addindent=’ ‘, newl=’\n’)

# 使用示例
config = ConfigManager(‘app_config.xml’)
print(“当前数据库配置:”, config.get_db_config())
print(“当前日志级别:”, config.get_log_level())

# 修改配置
config.set_db_config(host=’192.168.1.100′, port=’3306′)
config.set_log_level(‘DEBUG’)
config.save_config()

print(“修改后数据库配置:”, config.get_db_config())
4.2 案例2:XML数据转换工具
class XMLTransformer:
“””XML数据转换工具”””
def __init__(self):
self.transformations = {}

def register_transformation(self, xpath, func):
“””注册转换函数”””
self.transformations[xpath] = func

def transform(self, input_file, output_file):
“””执行转换”””
dom = minidom.parse(input_file)
root = dom.documentElement

for xpath, func in self.transformations.items():
# 简单的XPath模拟(实际项目中可以使用lxml)
nodes = self._find_nodes(root, xpath)
for node in nodes:
func(dom, node)

with open(output_file, ‘w’, encoding=’utf-8′) as f:
dom.writexml(f, indent=’ ‘, addindent=’ ‘, newl=’\n’)

def _find_nodes(self, root, xpath):
“””简单的节点查找(模拟XPath)”””
parts = xpath.split(‘/’)
nodes = [root]

for part in parts:
if not part:
continue
new_nodes = []
for node in nodes:
children = node.getElementsByTagName(part)
new_nodes.extend(children)
nodes = new_nodes

return nodes

# 使用示例
def convert_prices(dom, price_node):
“””价格转换函数:美元转人民币”””
price = float(price_node.firstChild.data)
rmb = price * 7.0
price_node.firstChild.data = f”{rmb:.2f}”

def add_currency(dom, price_node):
“””添加货币单位”””
parent = price_node.parentNode
currency = dom.createElement(‘currency’)
currency_text = dom.createTextNode(‘RMB’)
currency.appendChild(currency_text)
parent.insertBefore(currency, price_node.nextSibling)

# 创建转换器
transformer = XMLTransformer()
transformer.register_transformation(‘book/price’, convert_prices)
transformer.register_transformation(‘book/price’, add_currency)

# 执行转换
transformer.transform(‘books.xml’, ‘books_transformed.xml’)
print(“XML转换完成!”)
4.3 案例3:XML文档比较工具
class XMLComparator:
“””XML文档比较工具”””
def __init__(self):
self.differences = []

def compare(self, file1, file2):
“””比较两个XML文件”””
dom1 = minidom.parse(file1)
dom2 = minidom.parse(file2)

self.differences = []
self._compare_nodes(dom1.documentElement, dom2.documentElement, “”)

return self.differences

def _compare_nodes(self, node1, node2, path):
“””递归比较节点”””
# 检查节点类型
if node1.nodeType != node2.nodeType:
self.differences.append(f”类型不同: {path}”)
return

# 比较元素节点
if node1.nodeType == node1.ELEMENT_NODE:
if node1.tagName != node2.tagName:
self.differences.append(f”标签名不同: {path} – {node1.tagName} vs {node2.tagName}”)
return

# 比较属性
attrs1 = {node1.attributes.item(i).name: node1.attributes.item(i).value
for i in range(node1.attributes.length)}
attrs2 = {node2.attributes.item(i).name: node2.attributes.item(i).value
for i in range(node2.attributes.length)}

if attrs1 != attrs2:
self.differences.append(f”属性不同: {path}/{node1.tagName} – {attrs1} vs {attrs2}”)

# 比较子节点
children1 = [c for c in node1.childNodes if c.nodeType in (c.ELEMENT_NODE, c.TEXT_NODE)]
children2 = [c for c in node2.childNodes if c.nodeType in (c.ELEMENT_NODE, c.TEXT_NODE)]

if len(children1) != len(children2):
self.differences.append(f”子节点数量不同: {path}/{node1.tagName}”)
return

for i, (c1, c2) in enumerate(zip(children1, children2)):
new_path = f”{path}/{node1.tagName}[{i}]”
self._compare_nodes(c1, c2, new_path)

# 比较文本节点
elif node1.nodeType == node1.TEXT_NODE:
text1 = node1.data.strip()
text2 = node2.data.strip()
if text1 != text2:
self.differences.append(f”文本不同: {path} – ‘{text1}’ vs ‘{text2}’”)

# 使用示例
# 创建两个版本的XML
xml_v1 = “””

localhost 8080
“””

xml_v2 = “””

192.168.1.100 8080 30
“””

with open(‘config_v1.xml’, ‘w’) as f:
f.write(xml_v1)
with open(‘config_v2.xml’, ‘w’) as f:
f.write(xml_v2)

comparator = XMLComparator()
differences = comparator.compare(‘config_v1.xml’, ‘config_v2.xml’)

print(“发现差异:”)
for diff in differences:
print(f” – {diff}”)
4.4 案例4:XML数据验证器
class XMLValidator:
“””XML数据验证器”””
def __init__(self, schema_file=None):
self.schema_file = schema_file
self.errors = []

def validate_structure(self, xml_file, expected_structure):
“””验证XML结构”””
dom = minidom.parse(xml_file)
self.errors = []

def check_structure(node, structure, path=””):
if isinstance(structure, dict):
for tag, sub_structure in structure.items():
elements = node.getElementsByTagName(tag)
if not elements:
self.errors.append(f”缺少必需元素: {path}/{tag}”)
else:
for elem in elements:
check_structure(elem, sub_structure, f”{path}/{tag}”)
elif isinstance(structure, list):
# 结构是列表,验证数量
if len(node.getElementsByTagName(structure[0])) < 1: self.errors.append(f"缺少必需元素: {path}/{structure[0]}") check_structure(dom.documentElement, expected_structure) return len(self.errors) == 0 def validate_data_types(self, xml_file, type_rules): """验证数据类型""" dom = minidom.parse(xml_file) self.errors = [] for element_name, expected_type in type_rules.items(): elements = dom.getElementsByTagName(element_name) for elem in elements: if elem.firstChild: value = elem.firstChild.data try: if expected_type == 'int': int(value) elif expected_type == 'float': float(value) elif expected_type == 'date': # 简单日期验证 parts = value.split('-') if len(parts) != 3: raise ValueError except ValueError: self.errors.append(f"类型错误: {element_name} 应该是 {expected_type}") return len(self.errors) == 0 # 使用示例 validator = XMLValidator() # 定义期望的结构 expected_structure = { 'bookstore': { 'book': ['title', 'author', 'year', 'price'] } } # 定义类型规则 type_rules = { 'year': 'int', 'price': 'float' } # 验证 is_valid_structure = validator.validate_structure('books.xml', expected_structure) is_valid_types = validator.validate_data_types('books.xml', type_rules) print(f"结构验证: {'通过' if is_valid_structure else '失败'}") print(f"类型验证: {'通过' if is_valid_types else '失败'}") if validator.errors: print("错误详情:", validator.errors) 第五部分:最佳实践与注意事项 5.1 性能优化建议 避免频繁的DOM操作 :批量修改后再保存 使用节点缓存 :对频繁访问的节点进行缓存 选择合适的解析方式 :小文件用minidom,大文件考虑pulldom或lxml 及时释放资源 :处理完后及时清理DOM对象 5.2 安全注意事项 # 安全解析XML的示例 import xml.dom.minidom as minidom def safe_parse_xml(xml_string): """安全解析XML,防止XXE攻击""" # 禁用外部实体解析(虽然minidom默认不解析外部实体,但这是良好实践) try: dom = minidom.parseString(xml_string) return dom except Exception as e: print(f"XML解析错误: {e}") return None # 使用安全解析 xml_data = "test”
dom = safe_parse_xml(xml_data)
if dom:
print(“安全解析成功”)
5.3 错误处理最佳实践
def robust_xml_processing(xml_source):
“””健壮的XML处理示例”””
try:
# 尝试解析
if isinstance(xml_source, str):
if xml_source.strip().startswith(‘<'): dom = minidom.parseString(xml_source) else: dom = minidom.parse(xml_source) else: dom = minidom.parse(xml_source) # 验证基本结构 if not dom.documentElement: raise ValueError("空文档") # 处理业务逻辑 books = dom.getElementsByTagName('book') return books except minidom.DOMException as e: print(f"DOM异常: {e}") return [] except IOError as e: print(f"文件IO错误: {e}") return [] except Exception as e: print(f"未知错误: {e}") return [] # 使用 result = robust_xml_processing('books.xml') print(f"处理结果: {len(result)} 本书") 5.4 与其他库的对比 特性 xml.dom.minidom xml.etree.ElementTree lxml 标准性 W3C标准 Pythonic W3C标准+扩展 性能 中等 快 非常快 内存占用 高 中等 中等 XPath支持 有限 基础 完整 验证 无 无 完整 学习曲线 中等 低 中等 5.5 何时选择DOM 需要W3C标准兼容 :如处理命名空间、实体引用 需要随机访问和修改 :DOM提供完整的随机访问能力 文档结构复杂 :需要频繁遍历和修改树结构 需要与其他W3C技术集成 :如XSLT、XPath(虽然ElementTree也支持部分) 第六部分:总结 XML DOM在Python中是一个强大但常被忽视的工具。通过本文的详细解析,您应该已经掌握了: 基础操作 :解析、遍历、创建和修改XML 进阶技术 :命名空间、实体、大文件处理 实战应用 :配置文件管理、数据转换、文档比较 最佳实践 :性能优化、安全考虑、错误处理 虽然现在JSON更为流行,但在企业级应用、遗留系统集成、文档处理等领域,XML仍然发挥着重要作用。掌握XML DOM操作将为您的Python开发技能集增添重要的一环。 记住,选择合适的工具很重要:对于简单的数据交换,ElementTree可能更合适;对于需要严格标准支持或复杂文档操作的场景,DOM是更好的选择。在实际项目中,您也可以根据需求混合使用这些工具。 # Python XML DOM 实战应用案例解析 从基础到进阶的完整操作指南 引言:XML DOM 在现代开发中的地位 XML(可扩展标记语言)作为一种通用的数据交换格式,在企业级应用、配置文件、Web服务等领域仍然发挥着重要作用。DOM(Document Object Model)作为XML文档的标准解析接口,提供了一种树状结构来表示文档,使得开发者能够方便地遍历、修改和查询XML数据。 在Python中,标准库提供了 xml.dom 模块来处理XML文档。虽然相比 xml.etree.ElementTree ,DOM API可能显得稍微复杂,但它提供了更完整的W3C标准支持,特别是在需要处理命名空间、实体引用或进行复杂文档操作时表现出色。 第一部分:XML DOM 核心概念 1.1 XML DOM 核心概念 XML DOM将整个XML文档视为一个树状结构,每个元素、属性、文本节点都是树中的一个节点。理解以下核心概念至关重要: Document :DOM树的根节点,代表整个XML文档 Element :XML元素节点,可以包含子节点和属性 Attribute :元素的属性节点 Text :元素内的文本内容 Comment :注释节点 NodeList :节点列表,用于存储多个节点 1.2 Python DOM 模块介绍 Python标准库中的 xml.dom 模块提供了DOM解析功能,主要包含: minidom :轻量级DOM实现,适合大多数场景 pulldom :流式DOM解析,适合处理大文件 第二部分:基础操作实战 2.1 环境准备与安装 Python标准库已包含XML DOM支持,无需额外安装: import xml.dom.minidom from xml.dom.minidom import parse, parseString 2.2 解析XML文档 2.2.1 从文件解析XML import xml.dom.minidom as minidom # 准备示例XML文件内容 xml_content = """


Everyday Italian
Giada De Laurentiis
2005 30.00


Harry Potter
J.K. Rowling
2005 29.99

“””

# 将字符串写入临时文件进行演示
with open(‘books.xml’, ‘w’, encoding=’utf-8′) as f:
f.write(xml_content)

# 使用minidom解析XML文件
dom = minidom.parse(‘books.xml’)
print(“XML文档解析成功!”)
print(f”文档根元素: {dom.documentElement.tagName}”)
2.2.2 从字符串解析XML
# 直接从字符串解析
dom = minidom.parseString(xml_content)
print(“字符串解析成功!”)
2.3 遍历DOM树
2.3.1 获取节点信息
def print_node_info(node, indent=0):
“””递归打印节点信息”””
prefix = ” ” * indent
node_type = node.nodeType

if node_type == node.ELEMENT_NODE:
print(f”{prefix}元素节点: <{node.tagName}>“)
# 打印属性
if node.hasAttributes():
for attr_name, attr_value in node.attributes.items():
print(f”{prefix} 属性: {attr_name} = {attr_value}”)
elif node_type == node.TEXT_NODE:
text = node.data.strip()
if text:
print(f”{prefix}文本节点: ‘{text}’”)
elif node_type == node.COMMENT_NODE:
print(f”{prefix}注释节点: {node.data}”)

# 递归处理子节点
for child in node.childNodes:
print_node_info(child, indent + 1)

# 使用示例
dom = minidom.parseString(xml_content)
print_node_info(dom.documentElement)
2.3.2 使用节点列表
# 获取所有book元素
dom = minidom.parseString(xml_content)
books = dom.getElementsByTagName(‘book’)
print(f”找到 {books.length} 本书”)

# 遍历每本书
for i, book in enumerate(books):
print(f”\n第 {i+1} 本书:”)
# 获取title元素
title = book.getElementsByTagName(‘title’)[0]
print(f” 标题: {title.firstChild.data}”)

# 获取作者
author = book.getElementsByTagName(‘author’)[0]
print(f” 作者: {author.firstChild.data}”)
2.4 查找特定节点
2.4.1 getElementById 方法
# 注意:需要确保XML中有ID属性,且DTD定义了ID类型
xml_with_id = “””


Everyday Italian
Giada De Laurentiis
2005 30.00

“””

dom = minidom.parseString(xml_with_id)
# 如果XML有ID属性,可以通过getElementById获取
book = dom.getElementById(‘b1’)
if book:
print(f”找到ID为b1的元素: {book.tagName}”)
2.4.2 使用 getElementsByTagName
# 获取所有title元素
dom = minidom.parseString(xml_content)
titles = dom.getElementsByTagName(‘title’)

for title in titles:
# 获取父元素
book = title.parentNode
category = book.getAttribute(‘category’)
print(f”书籍分类: {category}, 标题: {title.firstChild.data}”)
2.5 创建和修改XML
2.5.1 创建新文档
def create_book_xml():
“””创建一个新的XML文档”””
# 创建DOM文档对象
impl = minidom.getDOMImplementation()
dom = impl.createDocument(None, ‘bookstore’, None)

# 获取根元素
root = dom.documentElement

# 创建第一个book元素
book1 = dom.createElement(‘book’)
book1.setAttribute(‘category’, ‘FICTION’)
root.appendChild(book1)

# 创建title元素
title = dom.createElement(‘title’)
title.setAttribute(‘lang’, ‘en’)
title_text = dom.createTextNode(‘The Great Gatsby’)
title.appendChild(title_text)
book1.appendChild(title)

# 创建author元素
author = dom.createElement(‘author’)
author_text = dom.createTextNode(‘F. Scott Fitzgerald’)
author.appendChild(author_text)
book1.appendChild(author)

# 创建year元素
year = dom.createElement(‘year’)
year_text = dom.createTextNode(‘1925’)
year.appendChild(year_text)
book1.appendChild(year)

# 创建price元素
price = dom.createElement(‘price’)
price_text = dom.createTextNode(‘12.99’)
price.appendChild(price_text)
book1.appendChild(price)

return dom

# 创建并保存
dom = create_book_xml()
with open(‘new_books.xml’, ‘w’, encoding=’utf-8′) as f:
dom.writexml(f, indent=’ ‘, addindent=’ ‘, newl=’\n’)
print(“新XML文档创建成功!”)
2.5.2 修改现有文档
# 修改现有XML
dom = minidom.parseString(xml_content)
books = dom.getElementsByTagName(‘book’)

# 修改第一本书的价格
first_book = books[0]
price_element = first_book.getElementsByTagName(‘price’)[0]
price_element.firstChild.data = ‘35.00’ # 修改价格

# 添加新属性
first_book.setAttribute(‘bestseller’, ‘true’)

# 添加新元素
discount = dom.createElement(‘discount’)
discount_text = dom.createTextNode(‘10%’)
discount.appendChild(discount_text)
first_book.appendChild(discount)

# 保存修改
with open(‘modified_books.xml’, ‘w’, encoding=’utf-8′) as f:
dom.writexml(f, indent=’ ‘, addindent=’ ‘, newl=’\n’)
print(“XML文档修改成功!”)
2.6 删除节点
# 删除节点示例
dom = minidom.parseString(xml_content)
books = dom.getElementsByTagName(‘book’)

# 删除第二本书
if books.length > 1:
second_book = books[1]
second_book.parentNode.removeChild(second_book)
print(“已删除第二本书”)

# 删除特定元素
first_book = books[0]
price_elements = first_book.getElementsByTagName(‘price’)
if price_elements.length > 0:
price_element = price_elements[0]
price_element.parentNode.removeChild(price_element)
print(“已删除价格元素”)

# 保存结果
with open(‘removed_books.xml’, ‘w’, encoding=’utf-8′) as f:
dom.writexml(f, indent=’ ‘, addindent=’ ‘, newl=’\n’)
第三部分:进阶操作与实战案例
3.1 处理XML命名空间
3.1.1 带命名空间的XML解析
# 带命名空间的XML示例
xml_ns = “””


Everyday Italian
Giada De Laurentiis
2005
30.00

“””

dom = minidom.parseString(xml_ns)

# 获取带命名空间的元素
books = dom.getElementsByTagNameNS(‘http://example.com/books’, ‘book’)
print(f”找到 {books.length} 本书(使用命名空间)”)

for book in books:
titles = book.getElementsByTagNameNS(‘http://example.com/books’, ‘title’)
if titles.length > 1:
title = titles[0]
print(f”标题: {title.firstChild.data}”)
3.1.2 创建带命名空间的元素
def create_namespaced_xml():
“””创建带命名空间的XML”””
impl = minidom.getDOMImplementation()
dom = impl.createDocument(‘http://example.com/books’, ‘ns:bookstore’, None)

root = dom.documentElement
root.setAttribute(‘xmlns:ns’, ‘http://example.com/books’)

# 创建带命名空间的元素
book = dom.createElementNS(‘http://example.com/books’, ‘ns:book’)
book.setAttribute(‘category’, ‘FICTION’)

title = dom.createElementNS(‘http://example.com/books’, ‘ns:title’)
title.setAttribute(‘lang’, ‘en’)
title_text = dom.createTextNode(‘The Great Gatsby’)
title.appendChild(title_text)
book.appendChild(title)

root.appendChild(book)

return dom

ns_dom = create_namespaced_xml()
with open(‘namespaced_books.xml’, ‘w’, encoding=’utf-8′) as f:
ns_dom.writexml(f, indent=’ ‘, addindent=’ ‘, newl=’\n’)
print(“带命名空间的XML创建成功!”)
3.2 处理实体引用
# XML实体引用示例
xml_with_entities = “””


]>


Python © Programming
Best book ™ for learning Python

“””

# 解析包含实体的XML
dom = minidom.parseString(xml_with_entities)
books = dom.getElementsByTagName(‘book’)

for book in books:
title = book.getElementsByTagName(‘title’)[0]
description = book.getElementsByTagName(‘description’)[0]
print(f”标题: {title.firstChild.data}”)
print(f”描述: {description.firstChild.data}”)
3.3 大型XML文件处理
3.3.1 使用 pulldom 处理大文件
import xml.dom.pulldom as pulldom

# 创建一个大型XML文件用于演示
def create_large_xml(filename, num_books=1000):
with open(filename, ‘w’, encoding=’utf-8′) as f:
f.write(‘\n’)
f.write(‘\n’)
for i in range(num_books):
f.write(f’ \n’)
f.write(f’ Book {i}\n’)
f.write(f’ Author {i % 10}\n’)
f.write(f’ {10 + i * 0.1:.2f}\n’)
f.write(f’
\n’)
f.write(‘
\n’)

# 使用pulldom处理大文件
def process_large_xml(filename):
“””使用pulldom流式处理大文件”””
event_stream = pulldom.parse(filename)
book_count = 0
expensive_books = []

for event, node in event_stream:
if event == pulldom.START_ELEMENT and node.tagName == ‘book’:
# 暂停流处理,展开当前节点
event_stream.expandNode(node)
price = node.getElementsByTagName(‘price’)[0].firstChild.data
if float(price) > 20.0:
title = node.getElementsByTagName(‘title’)[0].firstChild.data
expensive_books.append(title)
book_count += 1

print(f”找到 {book_count} 本价格超过20的书”)
return expensive_books

# 创建并处理大型XML
create_large_xml(‘large_books.xml’, 1000)
expensive_books = process_large_xml(‘large_books.xml’)
print(“部分高价书籍:”, expensive_books[:5])
3.4 XML与JSON转换
3.4.1 XML转JSON
import json

def xml_to_dict(node):
“””递归将XML节点转换为字典”””
if node.nodeType == node.TEXT_NODE:
return node.data.strip()

if node.nodeType != node.ELEMENT_NODE:
return None

result = {}

# 处理属性
if node.hasAttributes():
result[‘@attributes’] = {}
for i in range(node.attributes.length):
attr = node.attributes.item(i)
result[‘@attributes’][attr.name] = attr.value

# 处理子节点
children = []
text_content = []

for child in node.childNodes:
if child.nodeType == child.TEXT_NODE:
text = child.data.strip()
if text:
text_content.append(text)
else:
child_result = xml_to_dict(child)
if child_result is not None:
children.append((child.tagName, child_result))

# 如果有文本内容,直接返回
if text_content and not children:
return text_content[0] if len(text_content) == 1 else text_content

# 组织子节点
for tag_name, child_data in children:
if tag_name not in result:
result[tag_name] = child_data
else:
# 如果有多个同名节点,转换为列表
if not isinstance(result[tag_name], list):
result[tag_name] = [result[tag_name]]
result[tag_name].append(child_data)

return result

# 使用示例
dom = minidom.parseString(xml_content)
xml_dict = xml_to_dict(dom.documentElement)
json_str = json.dumps(xml_dict, indent=2, ensure_ascii=False)
print(“XML转JSON结果:”)
print(json_str)
3.4.2 JSON转XML
def dict_to_xml(parent, data, tag_name=None):
“””递归将字典转换为XML节点”””
if isinstance(data, dict):
# 处理属性
if ‘@attributes’ in data:
for attr_name, attr_value in data[‘@attributes’].items():
parent.setAttribute(attr_name, attr_value)
data = {k: v for k, v in data.items() if k != ‘@attributes’}

for key, value in data.items():
if isinstance(value, list):
for item in value:
dict_to_xml(parent, item, key)
else:
child = parent.ownerDocument.createElement(key)
parent.appendChild(child)
dict_to_xml(child, value, key)

elif isinstance(data, (str, int, float)):
if tag_name:
child = parent.ownerDocument.createElement(tag_name)
parent.appendChild(child)
text = parent.ownerDocument.createTextNode(str(data))
child.appendChild(text)
else:
text = parent.ownerDocument.createTextNode(str(data))
parent.appendChild(text)

# 使用示例
json_data = {
“bookstore”: {
“book”: [
{
“@attributes”: {“category”: “COOKING”},
“title”: {“@attributes”: {“lang”: “en”}, “#text”: “Everyday Italian”},
“author”: “Giada De Laurentiis”,
“year”: 2005,
“price”: 30.00
},
{
“@attributes”: {“category”: “CHILDREN”},
“title”: {“@attributes”: {“lang”: “en”}, “#text”: “Harry Potter”},
“author”: “J.K. Rowling”,
“year”: 2005,
“price”: 29.99
}
]
}
}

impl = minidom.getDOMImplementation()
dom = impl.createDocument(None, ‘root’, None)
root = dom.documentElement

dict_to_xml(root, json_data)
dom.documentElement = dom.documentElement.firstChild # 移除root包装

with open(‘from_json.xml’, ‘w’, encoding=’utf-8′) as f:
dom.writexml(f, indent=’ ‘, addindent=’ ‘, newl=’\n’)
print(“JSON转XML成功!”)
3.5 XML验证
3.5.1 使用DTD验证
# 创建带DTD的XML
xml_with_dtd = “””








]>


Everyday Italian
Giada De Laurentiis
2005 30.00

“””

# 验证XML(注意:minidom本身不提供验证功能,需要使用其他库如lxml)
# 这里展示如何检查基本结构
dom = minidom.parseString(xml_with_dtd)
books = dom.getElementsByTagName(‘book’)

for book in books:
required_elements = [‘title’, ‘author’, ‘year’, ‘price’]
missing = []
for elem in required_elements:
if book.getElementsByTagName(elem).length == 0:
missing.append(elem)

if missing:
print(f”警告: 书籍缺少元素: {missing}”)
else:
print(f”书籍结构完整: {book.getElementsByTagName(‘title’)[0].firstChild.data}”)
3.6 性能优化技巧
3.6.1 使用节点缓存
class XMLProcessor:
“””XML处理优化类”””
def __init__(self, dom):
self.dom = dom
self._cache = {}

def get_books_by_category(self, category):
“””缓存查询结果”””
cache_key = f”category_{category}”
if cache_key in self._cache:
return self._cache[cache_key]

books = []
all_books = self.dom.getElementsByTagName(‘book’)
for book in all_books:
if book.getAttribute(‘category’) == category:
books.append(book)

self._cache[cache_key] = books
return books

def get_book_price(self, book):
“””缓存价格计算”””
book_id = book.getAttribute(‘id’) if book.hasAttribute(‘id’) else None
if book_id:
cache_key = f”price_{book_id}”
if cache_key in self._cache:
return self._cache[cache_key]

price_elements = book.getElementsByTagName(‘price’)
if price_elements.length > 0:
price = float(price_elements[0].firstChild.data)
if book_id:
self._cache[cache_key] = price
return price
return None

# 使用示例
dom = minidom.parseString(xml_content)
processor = XMLProcessor(dom)

# 第一次查询
cooking_books = processor.get_books_by_category(‘COOKING’)
print(f”烹饪类书籍: {len(cooking_books)}”)

# 第二次查询(从缓存获取)
cooking_books_cached = processor.get_books_by_category(‘COOKING’)
print(f”烹饪类书籍(缓存): {len(cooking_books_cached)}”)
3.6.2 使用上下文管理器
from contextlib import contextmanager

@contextmanager
def xml_context(filename, mode=’r’):
“””XML文件处理上下文管理器”””
try:
if mode == ‘r’:
dom = minidom.parse(filename)
else:
impl = minidom.getDOMImplementation()
dom = impl.createDocument(None, ‘root’, None)
yield dom
finally:
# 清理工作
pass

# 使用上下文管理器
with xml_context(‘books.xml’) as dom:
books = dom.getElementsByTagName(‘book’)
print(f”找到 {books.length} 本书”)
第四部分:实战案例
4.1 案例1:配置文件管理器
class ConfigManager:
“””基于XML的配置文件管理器”””
def __init__(self, config_file):
self.config_file = config_file
self.dom = None
self.load_config()

def load_config(self):
“””加载配置文件”””
try:
self.dom = minidom.parse(self.config_file)
except FileNotFoundError:
# 创建默认配置
self.create_default_config()

def create_default_config(self):
“””创建默认配置”””
impl = minidom.getDOMImplementation()
self.dom = impl.createDocument(None, ‘configuration’, None)
root = self.dom.documentElement

# 添加数据库配置
db_config = self.dom.createElement(‘database’)
db_config.appendChild(self._create_element(‘host’, ‘localhost’))
db_config.appendChild(self._create_element(‘port’, ‘5432’))
db_config.appendChild(self._create_element(‘name’, ‘mydb’))
root.appendChild(db_config)

# 添加日志配置
log_config = self.dom.createElement(‘logging’)
log_config.appendChild(self._create_element(‘level’, ‘INFO’))
log_config.appendChild(self._create_element(‘file’, ‘app.log’))
root.appendChild(log_config)

self.save_config()

def _create_element(self, tag, text):
“””辅助方法:创建带文本的元素”””
elem = self.dom.createElement(tag)
text_node = self.dom.createTextNode(str(text))
elem.appendChild(text_node)
return elem

def get_db_config(self):
“””获取数据库配置”””
db_elem = self.dom.getElementsByTagName(‘database’)[0]
config = {}
for child in db_elem.childNodes:
if child.nodeType == child.ELEMENT_NODE:
config[child.tagName] = child.firstChild.data
return config

def set_db_config(self, **kwargs):
“””设置数据库配置”””
db_elem = self.dom.getElementsByTagName(‘database’)[0]
for key, value in kwargs.items():
elem = self.dom.getElementsByTagName(key)[0]
elem.firstChild.data = str(value)

def get_log_level(self):
“””获取日志级别”””
log_elem = self.dom.getElementsByTagName(‘logging’)[0]
level_elem = log_elem.getElementsByTagName(‘level’)[0]
return level_elem.firstChild.data

def set_log_level(self, level):
“””设置日志级别”””
log_elem = self.dom.getElementsByTagName(‘logging’)[0]
level_elem = log_elem.getElementsByTagName(‘level’)[0]
level_elem.firstChild.data = level

def save_config(self):
“””保存配置”””
with open(self.config_file, ‘w’, encoding=’utf-8′) as f:
self.dom.writexml(f, indent=’ ‘, addindent=’ ‘, newl=’\n’)

# 使用示例
config = ConfigManager(‘app_config.xml’)
print(“当前数据库配置:”, config.get_db_config())
print(“当前日志级别:”, config.get_log_level())

# 修改配置
config.set_db_config(host=’192.168.1.100′, port=’3306′)
config.set_log_level(‘DEBUG’)
config.save_config()

print(“修改后数据库配置:”, config.get_db_config())
4.2 案例2:XML数据转换工具
class XMLTransformer:
“””XML数据转换工具”””
def __init__(self):
self.transformations = {}

def register_transformation(self, xpath, func):
“””注册转换函数”””
self.transformations[xpath] = func

def transform(self, input_file, output_file):
“””执行转换”””
dom = minidom.parse(input_file)
root = dom.documentElement

for xpath, func in self.transformations.items():
# 简单的XPath模拟(实际项目中可以使用lxml)
nodes = self._find_nodes(root, xpath)
for node in nodes:
func(dom, node)

with open(output_file, ‘w’, encoding=’utf-8′) as f:
dom.writexml(f, indent=’ ‘, addindent=’ ‘, newl=’\n’)

def _find_nodes(self, root, xpath):
“””简单的节点查找(模拟XPath)”””
parts = xpath.split(‘/’)
nodes = [root]

for part in parts:
if not part:
continue
new_nodes = []
for node in nodes:
children = node.getElementsByTagName(part)
new_nodes.extend(children)
nodes = new_nodes

return nodes

# 使用示例
def convert_prices(dom, price_node):
“””价格转换函数:美元转人民币”””
price = float(price_node.firstChild.data)
rmb = price * 7.0
price_node.firstChild.data = f”{rmb:.2f}”

def add_currency(dom, price_node):
“””添加货币单位”””
parent = price_node.parentNode
currency = dom.createElement(‘currency’)
currency_text = dom.createTextNode(‘RMB’)
currency.appendChild(currency_text)
parent.insertBefore(currency, price_node.nextSibling)

# 创建转换器
transformer = XMLTransformer()
transformer.register_transformation(‘book/price’, convert_prices)
transformer.register_transformation(‘book/price’, add_currency)

# 执行转换
transformer.transform(‘books.xml’, ‘books_transformed.xml’)
print(“XML转换完成!”)
4.3 案例3:XML文档比较工具
class XMLComparator:
“””XML文档比较工具”””
def __init__(self):
self.differences = []

def compare(self, file1, file2):
“””比较两个XML文件”””
dom1 = minidom.parse(file1)
dom2 = minidom.parse(file2)

self.differences = []
self._compare_nodes(dom1.documentElement, dom2.documentElement, “”)

return self.differences

def _compare_nodes(self, node1, node2, path):
“””递归比较节点”””
# 检查节点类型
if node1.nodeType != node2.nodeType:
self.differences.append(f”类型不同: {path}”)
return

# 比较元素节点
if node1.nodeType == node1.ELEMENT_NODE:
if node1.tagName != node2.tagName:
self.differences.append(f”标签名不同: {path} – {node1.tagName} vs {node2.tagName}”)
return

# 比较属性
attrs1 = {node1.attributes.item(i).name: node1.attributes.item(i).value
for i in range(node1.attributes.length)}
attrs2 = {node2.attributes.item(i).name: node2.attributes.item(i).value
for i in range(node2.attributes.length)}

if attrs1 != attrs2:
self.differences.append(f”属性不同: {path}/{node1.tagName} – {attrs1} vs {attrs2}”)

# 比较子节点
children1 = [c for c in node1.childNodes if c.nodeType in (c.ELEMENT_NODE, c.TEXT_NODE)]
children2 = [c for c in node2.childNodes if c.nodeType in (c.ELEMENT_NODE, c.TEXT_NODE)]

if len(children1) != len(children2):
self.differences.append(f”子节点数量不同: {path}/{node1.tagName}”)
return

for i, (c1, c2) in enumerate(zip(children1, children2)):
new_path = f”{path}/{node1.tagName}[{i}]”
self._compare_nodes(c1, c2, new_path)

# 比较文本节点
elif node1.nodeType == node1.TEXT_NODE:
text1 = node1.data.strip()
text2 = node2.data.strip()
if text1 != text2:
self.differences.append(f”文本不同: {path} – ‘{text1}’ vs ‘{text2}’”)

# 使用示例
# 创建两个版本的XML
xml_v1 = “””

localhost 8080
“””

xml_v2 = “””

192.168.1.100 8080 30
“””

with open(‘config_v1.xml’, ‘w’) as f:
f.write(xml_v1)
with open(‘config_v2.xml’, ‘w’) as f:
f.write(xml_v2)

comparator = XMLComparator()
differences = comparator.compare(‘config_v1.xml’, ‘config_v2.xml’)

print(“发现差异:”)
for diff in differences:
print(f” – {diff}”)
4.4 案例4:XML数据验证器
class XMLValidator:
“””XML数据验证器”””
def __init__(self, schema_file=None):
self.schema_file = schema_file
self.errors = []

def validate_structure(self, xml_file, expected_structure):
“””验证XML结构”””
dom = minidom.parse(xml_file)
self.errors = []

def check_structure(node, structure, path=””):
if isinstance(structure, dict):
for tag, sub_structure in structure.items():
elements = node.getElementsByTagName(tag)
if not elements:
self.errors.append(f”缺少必需元素: {path}/{tag}”)
else:
for elem in elements:
check_structure(elem, sub_structure, f”{path}/{tag}”)
elif isinstance(structure, list):
# 结构是列表,验证数量
if len(node.getElementsByTagName(structure[0])) < 1: self.errors.append(f"缺少必需元素: {path}/{structure[0]}") check_structure(dom.documentElement, expected_structure) return len(self.errors) == 0 def validate_data_types(self, xml_file, type_rules): """验证数据类型""" dom = minidom.parse(xml_file) self.errors = [] for element_name, expected_type in type_rules.items(): elements = dom.getElementsByTagName(element_name) for elem in elements: if elem.firstChild: value = elem.firstChild.data try: if expected_type == 'int': int(value) elif expected_type == 'float': float(value) elif expected_type == 'date': # 简单日期验证 parts = value.split('-') if len(parts) != 3: raise ValueError except ValueError: self.errors.append(f"类型错误: {element_name} 应该是 {expected_type}") return len(self.errors) == 0 # 使用示例 validator = XMLValidator() # 定义期望的结构 expected_structure = { 'bookstore': { 'book': ['title', 'author', 'year', 'price'] } } # 定义类型规则 type_rules = { 'year': 'int', 'price': 'float' } # 验证 is_valid_structure = validator.validate_structure('books.xml', expected_structure) is_valid_types = validator.validate_data_types('books.xml', type_rules) print(f"结构验证: {'通过' if is_valid_structure else '失败'}") print(f"类型验证: {'通过' if is_valid_types else '失败'}") if validator.errors: print("错误详情:", validator.errors) 第五部分:最佳实践与注意事项 5.1 性能优化建议 避免频繁的DOM操作 :批量修改后再保存 使用节点缓存 :对频繁访问的节点进行缓存 选择合适的解析方式 :小文件用minidom,大文件考虑pulldom或lxml 及时释放资源 :处理完后及时清理DOM对象 5.2 安全注意事项 # 安全解析XML的示例 import xml.dom.minidom as minidom def safe_parse_xml(xml_string): """安全解析XML,防止XXE攻击""" # 禁用外部实体解析(虽然minidom默认不解析外部实体,但这是良好实践) try: dom = minidom.parseString(xml_string) return dom except Exception as e: print(f"XML解析错误: {e}") return None # 使用安全解析 xml_data = "test”
dom = safe_parse_xml(xml_data)
if dom:
print(“安全解析成功”)
5.3 错误处理最佳实践
def robust_xml_processing(xml_source):
“””健壮的XML处理示例”””
try:
# 尝试解析
if isinstance(xml_source, str):
if xml_source.strip().startswith(‘<'): dom = minidom.parseString(xml_source) else: dom = minidom.parse(xml_source) else: dom = minidom.parse(xml_source) # 验证基本结构 if not dom.documentElement: raise ValueError("空文档") # 处理业务逻辑 books = dom.getElementsByTagName('book') return books except minidom.DOMException as e: print(f"DOM异常: {e}") return [] except IOError as e: print(f"文件IO错误: {e}") return [] except Exception as e: print(f"未知错误: {e}") return [] # 使用 result = robust_xml_processing('books.xml') print(f"处理结果: {len(result)} 本书") 5.4 与其他库的对比 特性 xml.dom.minidom xml.etree.ElementTree lxml 标准性 W3C标准 Pythonic W3C标准+扩展 性能 中等 快 非常快 内存占用 高 中等 中等 XPath支持 有限 基础 完整 验证 无 无 完整 学习曲线 中等 低 中等 5.5 何时选择DOM 需要W3C标准兼容 :如处理命名空间、实体引用 需要随机访问和修改 :DOM提供完整的随机访问能力 文档结构复杂 :需要频繁遍历和修改树结构 需要与其他W3C技术集成 :如XSLT、XPath(虽然ElementTree也支持部分) 第六部分:总结 XML DOM在Python中是一个强大但常被忽视的工具。通过本文的详细解析,您应该已经掌握了: 基础操作 :解析、遍历、创建和修改XML 进阶技术 :命名空间、实体、大文件处理 实战应用 :配置文件管理、数据转换、文档比较 最佳实践 :性能优化、安全考虑、错误处理 虽然现在JSON更为流行,但在企业级应用、遗留系统集成、文档处理等领域,XML仍然发挥着重要作用。掌握XML DOM操作将为您的Python开发技能集增添重要的一环。 记住,选择合适的工具很重要:对于简单的数据交换,ElementTree可能更合适;对于需要严格标准支持或复杂文档操作的场景,DOM是更好的选择。在实际项目中,您也可以根据需求混合使用这些工具。