内容发布更新时间 : 2024/11/1 7:58:46星期一 下面是文章的全部内容请认真阅读。
import java.io.File;
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Document; import org.w3c.dom.Element;
public class OperateXml { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub OperateXml ox = new OperateXml(); ox.operateXml(); } public void operateXml() { try { DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File(\贷前核查输出模板.xml\ Element element = document.getDocumentElement(); // 得到所有表格集合 NodeList tblList = element.getElementsByTagName(\标签组 // 得到第一张表
Element tbl1 = (Element) tblList.item(0); // 得到第一张表中所有行 NodeList rowList = tbl1.getElementsByTagName(\ for (int i = 1; i < rowList.getLength(); i++) { Element rowNode = (Element) rowList.item(i); // 得到这行的所有单元格 NodeList cellList = rowNode.getElementsByTagName(\ // 基于这次模版开始从每行的第二个单元格操作 for (int j = 1; j < cellList.getLength(); j++) { if (j == 1) { Element cellNode = (Element) cellList.item(j); // 得到单元格底下的 文本(p节点) Element pNode = (Element) cellNode .getElementsByTagName(\ // 得到文本行 Element rNode = (Element) pNode.getElementsByTagName( \ //如果有文本值,那么修改,没有则给p节点追加r节点 if (rNode != null) { Node tNode = rNode.getElementsByTagName(\ .item(0); tNode.setTextContent(i+\ } else { Document parent = pNode.getOwnerDocument(); Element r = null; Element t = null; r = parent.createElement(\ t = parent.createElement(\ t.setTextContent(i+\ pNode.appendChild(r); r.appendChild(t); } } } } saveXml(\贷前核查输出模板1.doc\ } catch (Exception ex) {
System.out.println(\有误\ } }
public static void saveXml(String fileName, Document doc) {//将Document输出到文件 TransformerFactory transFactory=TransformerFactory.newInstance(); try {
Transformer transformer = transFactory.newTransformer(); transformer.setOutputProperty(\
}
}
DOMSource source=new DOMSource(); source.setNode(doc);
StreamResult result=new StreamResult();
result.setOutputStream(new FileOutputStream(fileName));
transformer.transform(source, result);
} catch (TransformerConfigurationException e){ e.printStackTrace();
} catch (TransformerException e) { e.printStackTrace();
} catch (FileNotFoundException e){ e.printStackTrace(); }