xml to word

从wordpress后台,导出所有文章,格式为xml。再将xml转为word。

import xml.etree.ElementTree as ET
from docx import Document

def xml_to_word(xml_file_path, word_file_path):
    try:
        # 解析 XML 文件
        tree = ET.parse(xml_file_path)
        root = tree.getroot()

        # 创建一个新的 Word 文档
        doc = Document()

        # 遍历 XML 元素并将文本添加到 Word 文档中
        for element in root.iter():
            if element.text and element.text.strip():
                doc.add_paragraph(element.text.strip())

        # 保存 Word 文档
        doc.save(word_file_path)
        print(f"成功将 {xml_file_path} 转换为 {word_file_path}")
    except Exception as e:
        print(f"转换过程中出现错误: {e}")

if __name__ == "__main__":
    # 使用原始字符串指定 XML 文件路径
    xml_file = r'C:\Users\Administrator\Desktop\download\WordPress.2025-03-18.xml'
    word_file = 'output.docx'
    xml_to_word(xml_file, word_file)

Leave a Reply