xml处理

写道
import java.io.File;
import java.io.FileOutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

@SuppressWarnings("unchecked")
public class Test {

public static void main(String agr[]) {
try {
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
SAXParser saxParser = saxFactory.newSAXParser();
MyHandler handler = new MyHandler();
saxParser.parse(new File("MyXml.xml"), handler);
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = (Document) builder.newDocument();
document.setXmlVersion("1.0");
Element study = document.createElement("学生成绩表");
document.appendChild(study);
String[] strs = handler.str;
int length = strs.length;
for (int k = 1; k <= length; k++) {
study.appendChild(document.createElement("学生"));
}
NodeList nodeList = document.getElementsByTagName("学生");
int size = nodeList.getLength();
for (int k = 0; k < size; k++) {
Node node = nodeList.item(k);
if (node.getNodeType() == Node.ELEMENT_NODE) {
node.appendChild(document.createElement("学生姓名"));
}
}
nodeList = document.getElementsByTagName("学生姓名");
size = nodeList.getLength();
for (int k = 0; k < size; k++) {
Node node = nodeList.item(k);
if (node.getNodeType() == Node.ELEMENT_NODE) {
node.appendChild(document.createTextNode(strs[k]));
}
}
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
File file = new File("新学生成绩表.xml");
FileOutputStream out = new FileOutputStream(file);
StreamResult xmlResult = new StreamResult(out);
transformer.transform(domSource, xmlResult);
} catch (Exception e) {
System.out.println(e);
}

}
}

class MyHandler extends DefaultHandler {
String[] str = new String[2];
boolean bool = false;
int i = 0;

@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
String text = new String(ch, start, length);
if (bool) {
str[i] = text.trim();
i++;
bool = false;
}
}

@Override
public void startElement(String uri, String localName, String qName,
Attributes atts) throws SAXException {
if (qName.equals("学生姓名")) {
bool = true;
}
}
}

 

你可能感兴趣的:(xml)