將 Word 轉換為 XML
談到 Office OpenXML,我們可能會想到 HTML。實際上,Office OpenXML 與 HTML 類似,都是基于標簽的語言。Office OpenXML 和 HTML 之間的區別在于 Office OpenXML 使用的標記不是預定義的。如果我們在 Office OpenXML 中創建自己的標簽,我們需要遵循一些規則。
首先,Office OpenXML 文檔中只包含一個根元素。根元素通常被視為文檔元素并出現在序言部分之后。此外,所有 Office OpenXML 元素都應包含結束標記。開始和結束標記都應該相同。此外,元素不能重疊。更重要的是,所有的屬性值都必須使用引號,我們不能在文本中使用一些特殊字符。遵循規則后,Office OpenXML 文檔將被格式化。
使用 C# 和 VB.NET 通過 Spire.Doc 將 Doc 轉換為 Office OpenXML
Spire.Doc ( Spire.Office ) 為您提供了一種將 Doc 轉換為 Office OpenXML 的簡單方法。這樣,我們只需點擊幾下,就可以將現有的 Word doc 文件轉換為 Office OpenXML 格式。現在,只需按照簡單的步驟。
第 1 步:創建項目
下載 Spire.Doc并安裝在系統上。通過 Visual Studio 創建一個項目并添加 Spire.Doc DLL 作為參考。
注意:請確保 Spire.Doc 和 Visual Studio 已正確安裝在系統上
第 2 步:加載 Word 文檔文件
加載我們需要轉換為 Office OpenXML 格式的本地 Word 文檔文件。下面的代碼可以幫助我們加載它:
Document document = new Document(); document.LoadFromFile(@"D:\Sample.doc");
第 3 步:將 Doc 轉換為 Office OpenXML
Spire.Doc 支持將 Word Doc 文件轉換為大多數流行的文件格式,例如 PDF、HTML、Office OpenXML、EPub、RTF、Dot、Text 等。現在,使用下面的代碼將 Word 轉換為 Office OpenXML。
document.SaveToFile("Sample.xml", FileFormat.Xml);
第 4 步:完整代碼
現在,將完整代碼寫入您的項目,然后按 F5 啟動程序。
[C#]
using System; using System.Windows.Forms; using Spire.Doc; using Spire.Doc.Documents; namespace to XML { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //Create word document Document document = new Document(); document.LoadFromFile(@"D:\Sample.doc"); //Save doc file. document.SaveToFile("Sample.xml", FileFormat.Xml); //Launching the MS Word file. WordDocViewer("Sample.xml"); } private void WordDocViewer(string fileName) { try { System.Diagnostics.Process.Start(fileName); } catch { } } } }
[VB.NET]
Imports System Imports System.Windows.Forms Imports Spire.Doc Imports Spire.Doc.Documents Namespace to XML Partial Public Class Form1 Inherits Form Public Sub New() InitializeComponent() End Sub Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) 'Create word document Dim document As New Document() document.LoadFromFile("D:\Sample.doc") 'Save doc file. document.SaveToFile("Sample.xml", FileFormat.Xml); 'Launching the MS Word file. WordDocViewer("Sample.xml") End Sub Private Sub WordDocViewer(ByVal fileName As String) Try System.Diagnostics.Process.Start(fileName) Catch End Try End Sub End Class End Namespace
運行演示后,您可能會在瀏覽器上找到一個 Office OpenXML 文檔: