对xml开展解析;进行增删改查还有schema验证
对xml进行解析;进行增删改查还有schema验证
现在网络上的关于解析xml的资料很多,但是利用schema解析的不是很多;所以我进行了下总结,包括xml的读取、分析、修改、查询。还有就是根据schema进行验证,当然,都是最基本的东西。
部分代码摘自:《core java volume2》,以及:http://blog.****.net/cds27/archive/2008/03/02/2139110.aspx
言语无用,直接上代码。
现在网络上的关于解析xml的资料很多,但是利用schema解析的不是很多;所以我进行了下总结,包括xml的读取、分析、修改、查询。还有就是根据schema进行验证,当然,都是最基本的东西。
部分代码摘自:《core java volume2》,以及:http://blog.****.net/cds27/archive/2008/03/02/2139110.aspx
言语无用,直接上代码。
<?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>
<?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>Xiangzhong</FIRST_NAME> <LAST_NAME>Chang</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>
package com.cxz.xml.dom; import java.io.File; 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 int FLAG_TRACE = 1; private static final int FLAG_INSERT = 2; private static final int FLAG_DELETE = 3; private static final int FLAG_UPDATE = 4; 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/freshman.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); } private void doSth(int flag) { switch (flag) { case FLAG_TRACE: traceDomTree(); break; case FLAG_INSERT: insertOneNode(); break; case FLAG_DELETE: deleteOneNode(); break; case FLAG_UPDATE: updateOneNode(); break; } } private void traceDomTree() {//遍历 NodeList children = root.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { 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()); } } private void insertOneNode() { Element theStudent = document.createElement("STUDENT"); theStudent.setAttribute("STUDENT_ID", "2003710201"); Element theElement = document.createElement("PASSWORD"); theElement.setTextContent("[137Joanna]"); theStudent.appendChild(theElement); theElement = document.createElement("FIRST_NAME"); theElement.setTextContent("Chang"); theStudent.appendChild(theElement); theElement = document.createElement("LAST_NAME"); theElement.setTextContent("Xiangzhong"); theStudent.appendChild(theElement); theElement = document.createElement("MAJOR_NUMBER"); theElement.setTextContent("1"); theStudent.appendChild(theElement); root.appendChild(theStudent); try { xml2File(root); validate(root); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void deleteOneNode() { Element theStudent = (Element) selectSingleNode( "/STUDENTS/STUDENT[@STUDENT_ID='3']", root); output(theStudent.getParentNode()); Node root = theStudent.getParentNode(); root.removeChild(theStudent); output(root); } private void updateOneNode() { Element theStudent = (Element) selectSingleNode( "/STUDENTS/STUDENT[FIRST_NAME='Miao']", root); output(theStudent.getParentNode()); theStudent.getElementsByTagName("MAJOR_NUMBER").item(0).setTextContent( "99999999999999999999"); output(theStudent.getParentNode()); } 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) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } 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; } private void xml2File(Node node) throws IOException, TransformerException { TransformerFactory tFactory = TransformerFactory.newInstance(); 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)); } private void validate(Node node) throws SAXException, IOException { SchemaFactory schemaFactory = SchemaFactory .newInstance("http://www.w3.org/2001/XMLSchema"); File xsdFile = new File("xml/students.xsd"); Schema schema = schemaFactory.newSchema(xsdFile); Validator validator = schema.newValidator(); Source source = new DOMSource(node); Result result = new DOMResult(); validator.validate(source, result); } 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 static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { DomParser parser = new DomParser(); parser.doSth(FLAG_TRACE); parser.doSth(FLAG_INSERT); parser.doSth(FLAG_DELETE); parser.doSth(FLAG_UPDATE); } }