这是java类文件。
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import org.xml.sax.SAXException;
import java.io.*;
public class Jaxp_1
{
public static void main(String [] args) throws Exception
{
Source schemaFile = new StreamSource(new File("xsd/img.xsd"));
Source xmlFile = new StreamSource(new File("xml/imgone.xml"));
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(schemaFile);
Validator validator = schema.newValidator();
try{
validator.validate(xmlFile);
System.out.println(xmlFile.getSystemId()+ " is valid");
System.out.println();
}
catch (SAXException e)
{
System.out.println(schemaFile.getSystemId() + " is NOT valid");
System.out.println("Reason: " + e.getMessage());
}
}
}
这是xml文件。
<?xml version="1.0" encoding="UTF-8"?>
<edge xmlns="http://www.example.org/img">
<image x="143.05" y="2" height="66" width="537"
xhref="/dccp_repository/dam/other/images/insurance.jpg" id="Image_48"
isLocked="false" rx="143.05" ry="2" rotation="0" />
</edge>
这是XSD文件。
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/img"
xmlns:tns="http://www.example.org/img" elementFormDefault="qualified">
<element name="edge">
<complexType>
<sequence>
<element name="image">
<complexType>
<attribute name="x" type="int"></attribute>
<attribute name="y" type="int"></attribute>
<attribute name="height" type="int"></attribute>
<attribute name="width" type="int"></attribute>
<attribute name="xhref" type="string"></attribute>
<attribute name="id" type="string"></attribute>
<attribute name="isLocked" type="string"></attribute>
<attribute name="rx" type="double"></attribute>
<attribute name="ry" type="int"></attribute>
<attribute name="rotation" type="int"></attribute>
</complexType>
</element>
</sequence>
</complexType>
</element>
</schema>
我改变了属性类型,如属性name =“x”type =“int”。我得到了错误:
file:/ D:/Maheshkumar.V/workspace/JavaOne/JavaIO/xsd/img.xsd无效 原因:cvc-datatype-valid.1.2.1:'143.05'不是'整数'的有效值。
它不会在异常中显示元素名称。整数在哪里?它没有特定的'图像'元素。
如果我有大的xml。我该如何识别错误?
答案 0 :(得分:1)
抛出的异常是SAXParseException,它是SAXException的子类。 SAXException无法告诉您故障发生的位置,但SAXParseException可以通过getLineNumber()和getColumnNumber()来告诉您。这些不会将元素命名为错误,但允许您通过其在xml文件中的位置来识别它。行号和列号指向元素的结束标记。
你可以用这个:
try{
validator.validate(xmlFile);
System.out.println(xmlFile.getSystemId()+ " is valid");
System.out.println();
} catch (SAXParseException e)
{
System.out.println(schemaFile.getSystemId() + " is NOT valid");
System.out.println("Reason: " + e.getMessage()
+ " at line:" + e.getLineNumber()
+ " at column:" + e.getColumnNumber() +".");
} catch (SAXException e)
{
System.out.println(schemaFile.getSystemId() + " is NOT valid");
System.out.println("Reason: " + e.getMessage());
}