package net.zj.xmlbeans.validation; |
|
import java.io.File; |
import java.io.IOException; |
import java.util.ArrayList; |
import java.util.Iterator; |
import org.apache.xmlbeans.XmlException; |
import org.apache.xmlbeans.XmlObject; |
import org.apache.xmlbeans.XmlOptions; |
import org.apache.xmlbeans.samples.validation.todolist.ItemType; |
import org.apache.xmlbeans.samples.validation.todolist.TodolistDocument; |
import org.apache.xmlbeans.samples.validation.todolist.TodolistDocument.Todolist; |
|
public class Validation { |
private static XmlOptions m_validationOptions; |
|
public boolean isValidAfterChanges(String xmlPath) { |
System.out.println("Validating after changes:"); |
// Set up the validation error listener. |
ArrayList<String> validationErrors = new ArrayList<String>(); |
m_validationOptions = new XmlOptions(); |
m_validationOptions.setErrorListener(validationErrors); |
|
TodolistDocument todoList = (TodolistDocument) parseXml(xmlPath, null); |
|
// Schema defines the <name> element as required (minOccurs = '1'). |
// Add an error. |
todoList.getTodolist().getItemArray(0).setName(null); |
|
// During validation, errors are added to the ArrayList for |
// retrieval and printing by the printErrors method. |
boolean isValid = todoList.validate(m_validationOptions); |
|
if (!isValid) { |
printErrors(validationErrors); |
} |
return isValid; |
} |
|
public boolean isValidOnTheFly(String xmlPath) { |
System.out.println("Validating on-the-fly:"); |
m_validationOptions = new XmlOptions(); |
m_validationOptions.setValidateOnSet(); |
|
TodolistDocument todoList = (TodolistDocument) parseXml(xmlPath, |
m_validationOptions); |
Todolist list = todoList.getTodolist(); |
ItemType firstItem = list.getItemArray(0); |
|
// Schema defines the <id> element as allowing values up to 100. |
// Add an error. |
firstItem.setId(8587); |
|
// This line will not be reached. |
return todoList.validate(); |
} |
|
public void printErrors(ArrayList<String> validationErrors) { |
System.out.println("Errors discovered during validation:"); |
Iterator<String> iter = validationErrors.iterator(); |
while (iter.hasNext()) { |
System.out.println(">> " + iter.next() + "
"); |
} |
} |
|
public XmlObject parseXml(String xmlFilePath, XmlOptions validationOptions) { |
File xmlFile = new File(xmlFilePath); |
XmlObject xml = null; |
try { |
xml = XmlObject.Factory.parse(xmlFile, validationOptions); |
} catch (XmlException e) { |
e.printStackTrace(); |
} catch (IOException e) { |
e.printStackTrace(); |
} |
return xml; |
} |
|
public static void main(String[] args) { |
Validation thisSample = new Validation(); |
String xmlPath = "docs/todolist.xml"; |
|
// Use the validate method to validate an instance after |
// updates. |
thisSample.isValidAfterChanges(xmlPath); |
|
// Use the VALIDATE_ON_SET option to validate an instance |
// as updates are made. |
thisSample.isValidOnTheFly(xmlPath); |
} |
} |