0
我嘗試從xml文件解析文本,然後寫入並保存在docx文件與apachepoi XWPFDocument,它創建docx文件,但它是空的,我無法看到我的文本從解析XML文件。任何建議將不勝感激?寫在docx文件
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);
}