java schema 增删改查

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
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.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;

public class DomParser {
	private static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
	private static String W3C_XML_SCHEMA = "http://www.w3c.org/2001/XMLSchema";
	private static String W3C_APACHE = "http://apache.org/xml/features/validation/schema";
	File xmlFile = new File("xml/dest.xml");  //源文件
	DocumentBuilderFactory xmlfactory = null;
	DocumentBuilder builder = null;
	Document document = null;
	Element root = null;

	public DomParser() throws ParserConfigurationException, SAXException,
			IOException {
		xmlfactory = DocumentBuilderFactory.newInstance();
		xmlfactory.setValidating(true);
		xmlfactory.setNamespaceAware(true);
		xmlfactory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
		xmlfactory.setFeature(W3C_APACHE, true);
		xmlfactory.setIgnoringElementContentWhitespace(true);
		builder = xmlfactory.newDocumentBuilder();
		builder.setErrorHandler(new MyXmlErrorHandler());
		builder = xmlfactory.newDocumentBuilder();
		document = builder.parse(xmlFile);
		root = document.getDocumentElement();
		removeWhilespace(root);
	}

	/**
	 * @param express 节点路径
	 * @param source 根节点
	 * @return 返回指定节点
	 */
	private Node selectSingleNode(String expression, Object source) {
		XPathFactory xPathFactory = XPathFactory.newInstance();
		XPath xPath = xPathFactory.newXPath();
		Node result = null;
		try {
			result = (Node) xPath.evaluate(expression, source,
					XPathConstants.NODE);
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * @param express 节点路径
	 * @param source 根节点
	 * @return 返回指定节点下的所有结果集
	 */
	public static NodeList selectNodes(String express, Object source) {
		NodeList result = null;
		XPathFactory xpathFactory = XPathFactory.newInstance();
		XPath xpath = xpathFactory.newXPath();
		try {
			result = (NodeList) xpath.evaluate(express, source,
					XPathConstants.NODESET);
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 将修改或增加过记录的xml写入源文件
	 * @param node 已经被改变的根节点
	 */
	private void xml2File(Node node) {
		TransformerFactory tFactory = TransformerFactory.newInstance();
		try {
			Transformer transformar = tFactory.newTransformer();
			File file = new File("xml/dest.xml"); //目标文件
			file.createNewFile();
			Source source = new DOMSource(node);
			FileOutputStream out = new FileOutputStream(file);
			transformar.transform(source, new StreamResult(out));
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据.xsd文件校验参数类型是否合法
	 * @param node 根节点参数
	 */
	private void validate(Node node) {
		SchemaFactory schemaFactory = SchemaFactory
				.newInstance("http://www.w3.org/2001/XMLSchema");
		File xsdFile = new File("xml/students.xsd"); //校验文件
		try {
			Schema schema = schemaFactory.newSchema(xsdFile);
			Validator validator = schema.newValidator();
			Source source = new DOMSource(node);
			Result result = new DOMResult();
			validator.validate(source, result);
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private int removeWhilespace(Element element) {
		int count = 0;
		NodeList children = element.getChildNodes();
		if (children.getLength() <= 1) {
			return 0;
		} else {
			for (int i = children.getLength() - 1; i >= 0; i--) {
				Node child = children.item(i);
				if (child instanceof Text
						&& ((Text) child).getData().trim().length() == 0) {
					element.removeChild(child);
					count++;
				} else if (child instanceof Element) {
					count += removeWhilespace((Element) child);
				}
			}
		}
		return count;
	}

	public static void output(Node node) {
		TransformerFactory transFactory = TransformerFactory.newInstance();
		try {
			Transformer transformer = transFactory.newTransformer();
			transformer.setOutputProperty("indent", "yes");

			DOMSource source = new DOMSource();
			source.setNode(node);
			StreamResult result = new StreamResult();
			result.setOutputStream(System.out);

			transformer.transform(source, result);
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 查询所有记录
	 */
	public void traceDomTree() {
		NodeList children = root.getChildNodes();
		for (int i = 0; i < children.getLength(); i++) {
			System.out.println("第"+(i+1)+"条记录:");
			Element child = (Element) children.item(i);
			Element element = (Element) child.getFirstChild();
			while (element.getNextSibling() != null) {
				System.out.println(element.getTextContent());
				element = (Element) element.getNextSibling();
			}
			System.out.println(element.getTextContent());
		}
	}

	/**
	 * 插入一条记录
	 */
	public void insertOneNode() {
		Element theStudent = document.createElement("STUDENT");
		theStudent.setAttribute("STUDENT_ID", "11111");

		Element theElement = document.createElement("PASSWORD");
		theElement.setTextContent("1234567");
		theStudent.appendChild(theElement);

		theElement = document.createElement("FIRST_NAME");
		theElement.setTextContent("双江");
		theStudent.appendChild(theElement);

		theElement = document.createElement("LAST_NAME");
		theElement.setTextContent("李");
		theStudent.appendChild(theElement);

		theElement = document.createElement("MAJOR_NUMBER");
		theElement.setTextContent("14");
		theStudent.appendChild(theElement);

		root.appendChild(theStudent);
		validate(root);
		xml2File(root);
	}

	/**
	 * 删除一条记录
	 */
	public void deleteOneNode(int studentId) {
		Element theStudent = (Element) selectSingleNode(
				"/STUDENTS/STUDENT[@STUDENT_ID='"+studentId+"']", root);
		Node root = theStudent.getParentNode();
		root.removeChild(theStudent);
		validate(root);
		xml2File(root);
	}

	/**
	 * 更新一条记录
	 */
	public void updateOneNode() {
		Element theStudent = (Element) selectSingleNode(
				"/STUDENTS/STUDENT[FIRST_NAME='Miao']", root);
		theStudent.getElementsByTagName("MAJOR_NUMBER").item(0).setTextContent(
				"44");
		validate(root);
		xml2File(root);
	}
	
	public static void main(String[] args) throws ParserConfigurationException,
			SAXException, IOException {
		DomParser parser = new DomParser();
		parser.updateOneNode();
		parser.traceDomTree();
	}
}

import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class MyXmlErrorHandler implements ErrorHandler {

	@Override
	public void error(SAXParseException exception) throws SAXException {
		exception.printStackTrace();
	}

	@Override
	public void fatalError(SAXParseException exception) throws SAXException {
		exception.printStackTrace();
	}

	@Override
	public void warning(SAXParseException exception) throws SAXException {
		exception.printStackTrace();
	}
}



dest.xml文件如下:
<?xml version="1.0" encoding="UTF-8"?>  
<STUDENTS xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:noNamespaceSchemaLocation="students.xsd">  
    <STUDENT STUDENT_ID="1">  
        <PASSWORD>19841230</PASSWORD>  
        <FIRST_NAME>建斌</FIRST_NAME>  
        <LAST_NAME>成</LAST_NAME>  
        <MAJOR_NUMBER>7</MAJOR_NUMBER>  
    </STUDENT>  
    <STUDENT STUDENT_ID="2">  
        <PASSWORD>19841230</PASSWORD>  
        <FIRST_NAME>Miao</FIRST_NAME>  
        <LAST_NAME>Wu</LAST_NAME>  
        <MAJOR_NUMBER>7</MAJOR_NUMBER>  
    </STUDENT>  
    <STUDENT STUDENT_ID="3">  
        <PASSWORD>19841230</PASSWORD>  
        <FIRST_NAME>Juntai</FIRST_NAME>  
        <LAST_NAME>Wang</LAST_NAME>  
        <MAJOR_NUMBER>7</MAJOR_NUMBER>  
    </STUDENT>  
</STUDENTS>



students.xml格式文件如下:
<?xml version="1.0" encoding="UTF-8"?>  
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"  
    elementFormDefault="qualified">  
    <xs:element name="STUDENTS" type="students-type" />  
    <xs:complexType name="students-type">  
        <xs:sequence maxOccurs="unbounded">  
            <xs:element name="STUDENT" type="student-type" />  
        </xs:sequence>  
    </xs:complexType>  
    <xs:complexType name="student-type">  
        <xs:sequence>  
            <xs:element name="PASSWORD" type="xs:string" />  
            <xs:element name="FIRST_NAME" type="xs:string" />  
            <xs:element name="LAST_NAME" type="xs:string" />  
            <xs:element name="MAJOR_NUMBER" type="xs:integer" />  
            <xs:any minOccurs="0" />  
        </xs:sequence>  
        <xs:attribute name="STUDENT_ID" type="xs:integer" use="required"/>  
    </xs:complexType>  
</xs:schema>



你可能感兴趣的:(java,schema)