2013-12-10 68 views
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); 
     } 

回答

1

根據我XWPFRun的經驗,當你這樣做:

paragraphOneRunOne.setText(in); 

'關於在' 需要爲等於文本你想要輸入。您「在」等於如下:

in = new BufferedReader(new FileReader("D:\\Probe.xml")); 

首先嚐試解析文本,然後設置,作爲你的性格來看,是這樣的:

String in = textFromXMLFile 
paragraphOneRunOne.setText(in); 

或者,如果我理解正確的代碼(我沒有做任何XML還)和ArrayList包含的文字,是這樣的:

List<Elementt> empList = new ArrayList<>(); 
for(int i = 0; i < empList.length(); i++){ 
    paragraphOneRunOne.setText(empList.get(i)); 
} 

主要的一點是,只要你設置runtext,不管你在這一點上使用似乎是什麼inpu因此,在設置運行之前,需要準備好相關數據。

祝你好運!