用C#写一个word文档内容转换成XML的winform程序
时间: 2024-12-26 16:28:26 浏览: 4
在C#中,我们可以使用`DocumentFormat.OpenXml`库来处理Word文档的内容,并将其转换为XML。这是一个简单的WinForm程序示例,它将读取Word文档并保存其内容到XML文件:
```csharp
using System;
using System.IO;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void ConvertButton_Click(object sender, EventArgs e)
{
if (OpenFileDialog.ShowDialog() == DialogResult.OK)
{
string wordFilePath = openFileDialog.FileName;
string xmlFilePath = Path.ChangeExtension(wordFilePath, ".xml");
using WordprocessingDocument doc = WordprocessingDocument.Open(wordFilePath, true);
MainDocumentPart mainDocPart = doc.MainDocumentPart;
// 获取并保存所有段落的内容
var paragraphs = mainDocPart.Document.Body.Elements<Paragraph>();
StringBuilder xmlContent = new StringBuilder();
foreach (var paragraph in paragraphs)
{
xmlContent.AppendLine($"<{paragraph.Tag}>{paragraph.InnerText}</{paragraph.Tag}>");
}
File.WriteAllText(xmlFilePath, xmlContent.ToString());
MessageBox.Show("Word文档已成功转换为XML.");
}
}
}
阅读全文