【发布时间】:2013-12-10 14:14:56
【问题描述】:
我尝试从 xml 文件中解析文本,然后将其写入并使用 apachepoi XWPFDocument 保存在 docx 文件中,它会创建 docx 文件,但它是空的,我无法从解析的 xml 中看到我的文本。任何建议将不胜感激?
xml:
`<document>
<el id="1">
<text>Rakesh</text>
</el>
<el id="2">
<text>John</text>
</el>
<el id="3">
<text>Rajesh</text>
</el>
</document>`
代码:
public void dothis() throws ParserConfigurationException, SAXException,
IOException, TransformerFactoryConfigurationError,
TransformerException {
in = new BufferedReader(new FileReader("D:\\Probe.xml"));
XWPFDocument document1 = new XWPFDocument();
XWPFParagraph paragraphOne = document1.createParagraph();
XWPFRun paragraphOneRunOne = paragraphOne.createRun();
paragraphOneRunOne.setText(in);
PrintWriter zzz = new PrintWriter(new FileWriter("D:\\dd3.docx"));
document1.write(zzz);
zzz.close();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Get the DOM Builder
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("D:\\Probe.xml");
List<Elementt> empList = new ArrayList<>();
// Iteration durch den Knoten und die kinder Knoten extraktion
NodeList nodeList = document.getDocumentElement().getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node instanceof Element) {
Elementt emp = new Elementt();
emp.id = node.getAttributes().getNamedItem("id").getNodeValue();
NodeList childNodes = node.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
Node cNode = childNodes.item(j);
// Unterelementen von xml identifizieren
if (cNode instanceof Element) {
String content = cNode.getLastChild().getTextContent()
.trim();
switch (cNode.getNodeName()) {
case "text":
emp.text = content;
break;
}
}
}
empList.add(emp);
}
【问题讨论】:
标签: java xml apache-poi docx