dom方式解析XML输出为CSV

  之前一篇 借助DOM4J完成了解析工作,下面采用原始的DOM方式完成相同的工作,如果运行不了,你可能还需要导入xalan.jar包。

import java.io.File;
import java.io.PrintWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.xpath.XPathAPI;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DomTest {
	public static void main(String[] args) throws Exception {
		DocumentBuilderFactory domFactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
		Document doc = domBuilder.parse(new File("I:\\test2.xml"));
		//XPathAPI需要xalan.jar支持
		NodeList recordlist=XPathAPI.selectNodeList(doc, "records/record");
		PrintWriter pWriter=new PrintWriter("I:\\hello2.csv");
		String tempString;
		NodeList phyNodeList=XPathAPI.selectNodeList(doc, "records/record[1]/field/@lname");
		for (int i = 0; i < phyNodeList.getLength(); i++) {
			tempString=new String(phyNodeList.item(i).getNodeValue().getBytes("UTF-8"),"UTF-8");
			if (i==phyNodeList.getLength()-1) {
				pWriter.print(tempString);
			}else {
				pWriter.print(tempString+",");
			}
		}
		pWriter.println();
		for(int i=0;i<recordlist.getLength();i++){
			NodeList fieldlist=XPathAPI.selectNodeList(recordlist.item(i), "field");
			for (int j = 0; j < fieldlist.getLength(); j++) {
				Element element=(Element)fieldlist.item(j);
				tempString=new String (element.getFirstChild().getNodeValue().getBytes("UTF-8"),"UTF-8");
				if (j==fieldlist.getLength()-1) {
					pWriter.print(tempString);
				}else
				pWriter.print(tempString+",");
			}
			pWriter.println();
		}
		pWriter.close();
	}
}

 运行后同样达到预期效果:

你可能感兴趣的:(xml,csv,XPathAPI)