java解析odt_java - 使用Java从odt文件读取XForm - 堆栈内存溢出

轩辕煌
2023-12-01

我设法通过jdom(odfdom-java)做到了这一点,毕竟一点都没有使用过。 绑定的xml本身存在于表示odt的xml中。 您只需要知道表单的ID或标签的名称,即可获得正确的节点。 之后,将构造一个字符串,其中包含带有表单数据的xml。 我的代码如下:

import org.apache.xerces.dom.DeepNodeListImpl;

import org.apache.xml.serialize.OutputFormat;

import org.apache.xml.serialize.XMLSerializer;

import org.w3c.dom.Document;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import java.io.IOException;

import java.util.Enumeration;

import java.util.zip.ZipEntry;

import java.util.zip.ZipFile;

public class TestXFormData {

private static StringBuilder nodeContent;

public static void main(String[] args) throws Exception {

//Unzip the openOffice Document

ZipFile zipFile = new ZipFile("C://myFile.odt");

Enumeration entries = zipFile.entries();

ZipEntry entry;

while(entries.hasMoreElements()) {

entry = (ZipEntry) entries.nextElement();

if (entry.getName().equals("content.xml")) {

// construct document

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();

domFactory.setNamespaceAware(true);

DocumentBuilder docBuilder = domFactory.newDocumentBuilder();

Document doc = docBuilder.parse(zipFile.getInputStream(entry));

// print the document

printDocument(doc);

// get the node

NodeList list = doc.getElementsByTagName("myTagName");

Node node = ((DeepNodeListImpl) list).item(0);

nodeContent = new StringBuilder();

// print the xml with the form data

prettyPrint(node);

System.out.println(nodeContent.toString());

}

}

}

private static void prettyPrint(Node node) {

if (node.getNodeType() == Node.TEXT_NODE) {

nodeContent.append(node.getNodeValue());

} else if (node.getNodeType() == Node.ELEMENT_NODE) {

nodeContent.append("");

NodeList kids = node.getChildNodes();

for (int i = 0; i < kids.getLength(); i++) {

prettyPrint(kids.item(i));

}

nodeContent.append("" + node.getNodeName() + ">");

}

}

private static void printDocument(Document doc) throws IOException {

OutputFormat format = new OutputFormat(doc);

format.setIndenting(true);

XMLSerializer serializer = new XMLSerializer(System.out, format);

serializer.serialize(doc);

}

}

 类似资料: