技术开发 频道

Office文件格式突变,促使Java和Office更完美集成



@Test public void fromDocumentIntoDOM() throws Exception { ZipFile docxFile = new ZipFile(new File("test.docx")); ZipEntry documentXML = docxFile.getEntry("word/document.xml"); InputStream documentXMLIS = docxFile.getInputStream(documentXML); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); Document doc = dbf.newDocumentBuilder().parse(documentXMLIS); assertEquals("[w:document: null]", doc.getDocumentElement().toString()); }
 下面让我们看一下test.docx中最主要的document.xml,这个文档看上去要比一般的xml文档更丰富,它可以表示word2007的所有的格式,也面是document.xml文档的内容(删除了一些命名空间):

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document><w:body><w:pw:rsidR="00A77011" w:rsidRDefault="004333E8"><w:pPr><w:rPr><w:rFonts w:hint="eastAsia"/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:hint="eastAsia"/></w:rPr><w:t>这是第一个测试文档</w:t></w:r></w:p><w:sectPr w:rsidR="00A77011" w:rsidSect="00A77011"><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1800" w:bottom="1440" w:left="1800" w:header="851" w:footer="992" w:gutter="0"/><w:cols w:space="425"/><w:docGrid w:type="lines" w:linePitch="312"/></w:sectPr></w:body></w:document>
 
    至于document.xml中每个节点和属性的详细信息已不属于本文所讨论内容,感兴趣的读者可以参考OpenXML文档格式。虽然我们不太清楚整个文档的格式,但这个文档的核心部分是相当清楚的。如"p"表示段、"r"表示文本范围。我们还可以在document.xml中找到输入的文本"这是第一个测试文档"。
 
    现在我们已经基本了解document.xml的内容,也面我们就来编辑这些内容。在前面讲来使用ZipFile和ZipEntry来读取document.xml的数据,但用它们来写数据有一些困难。
 
除了用这两个类来操作document.xml外,我们还可以使用ZipOutputStream来向document.xml中写入数据。当然,我们还可以用其他的第三方工具来处理。但在本文中选用了ZipOutputStream,因为这个类的JDK的一部分。
 
    要想操作document.xml,必须得做以下几件事。首先,Java应用程序必须通过DOM的层次关系来枚举数据,先查找到"t"结点,然后在这个节点上插入自己的内容,并将其写回document.xml。为了更容易操作XML,开发都必须创建一个Transformer对象,并将数据包装在ByteArrayOutputStream中。
0
相关文章