论坛首页 Java企业应用论坛

Schema 校验XML某些属性不可重复

浏览 4980 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2007-12-19  
问题的提出:
当xml文件包含多个相同元素时,如果这些元素的字段在该属性值上有重复,则不能通过Schema验证。

问题的分类:
根据不能重复的元素或者属性所在位置,可以分为下面3种情况
1. 不同元素的某个属性不能重复
2. 不同元素的某个子元素不能重复
3. 一个元素的多个子元素不能重复

解决方法举例:
XML文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<persons>
  <person name="walnut">  -->不同person的name属性不能重复
    <id>13130198201200770</id>  -->不同person的id子元素不能重复
    <children>
      <child>aaa</child>  -->children的不同child不能重复
      <child>bbb</child>
<child>ccc</child>
    </children>
  </person>
  <person name="daisy">
<id>13130198201200775</id>
<children>
<child>ccc</child>
    </children>
  </person>
</persons>

用于校验的XSD文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"  elementFormDefault="qualified" attributeFormDefault="qualified">

<xsd:element name="persons">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="person" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<xsd:unique name="nameUnique">
                        <xsd:selector   xpath=".//person"/>
                        <xsd:field   xpath="@name"/>
                </xsd:unique>
<xsd:unique name="idUnique">
                        <xsd:selector   xpath=".//person"/>
                        <xsd:field   xpath="id"/>
                </xsd:unique>

</xsd:element>

<xsd:element name="person">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="id" type="xsd:string"/>
<xsd:element ref="children" minOccurs="0" maxOccurs="1"/>
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string"/>
</xsd:complexType>

</xsd:element>

<xsd:element name="children">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="child" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<xsd:unique name="childUnique">
<xsd:selector xpath=".//child"/>
<xsd:field xpath="."/>
</xsd:unique>
</xsd:element>

</xsd:schema>

利用xsd文件校验xml文件的java代码:

public class XMLValidateUtil {

	private static Logger logger = Logger.getLogger(XMLValidateUtil.class);

	/**
	 * 利用xsd文件验证xml文件的结构合法性
	 * 
	 * @param xmlFileName
	 * @param xsdFileName
	 * @return
	 */
	public static boolean validateXMLByXSD(String xmlFileName, String xsdFileName) {

		if (xmlFileName == null || xmlFileName.length() < 1) {
			return false;
		}

		if (xsdFileName == null || xsdFileName.length() < 1) {
			return false;
		}
		try {
			XMLErrorHandler errorHandler = new XMLErrorHandler();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			factory.setValidating(true);// 注意要设置有效,否则后面验证无用
			// factory.setNamespaceAware(true);//XSD中有命名空间设置
			SAXParser parser = factory.newSAXParser();
			SAXReader xmlReader = new SAXReader();
			org.dom4j.Document documentObject = (org.dom4j.Document) xmlReader
					.read(new File(xmlFileName));// filename是对应符合XSD模式的具体xml文件绝对路径名

			// String xsdpathfile = "e:\\schemaexample\\example.xsd";//xsdPathfile是绝对路径名
			parser.setProperty(
					"http://java.sun.com/xml/jaxp/properties/schemaLanguage",
					"http://www.w3.org/2001/XMLSchema");
			parser.setProperty(
					"http://java.sun.com/xml/jaxp/properties/schemaSource",
					"file:" + xsdFileName);
			SAXValidator validator = new SAXValidator(parser.getXMLReader());
			validator.setErrorHandler(errorHandler);
			validator.validate(documentObject);
			XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());
			if (errorHandler.getErrors().hasContent()) {
				writer.write(errorHandler.getErrors());
				return false;
			} else {
				logger.info("xml validate success by xsd.");
				return true;
			}
		} catch (Exception ex) {
			logger.error("xml file: "+xmlFileName+" validate failed by xsd file:"+xsdFileName+" because "+ex.getMessage());
			return false;
		}
	}

	public static void main(String[] args) {
		
		String xmlFile="C:\\myxml.xml";
		String xsdFile="C:\\myxsd.xsd";
		XMLValidateUtil.validateXMLByXSD(xmlFile,xsdFile);
		
	}

}


论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics