Java_XmlSchema_Validate

xml file

<EODPriceSnapshots xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://api.company.com/">
    <MessageInfo>
        <MessageCode>200</MessageCode>
        <MessageDetail>Request data successfully</MessageDetail>
    </MessageInfo>
    <GeneralInfo>
        <ShareClassId>0P000xxxx</ShareClassId>
        <CompanyName>International Business Machines Corp</CompanyName>
        <ExchangeId>xxx</ExchangeId>
        <Symbol>yyy</Symbol>
        <CUSIP>888888</CUSIP>
        <CIK>11111</CIK>
        <ISIN>US3333</ISIN>
        <SEDOL>2005973</SEDOL>
        <CountryId>uuu</CountryId>
    </GeneralInfo>
    <EODPriceSnapshotEntity>
        <TradingDate>2016-09-07</TradingDate>
        <OpenPrice>160.19</OpenPrice>
        <HighPrice>161.76</HighPrice>
        <LowPrice>160</LowPrice>
        <ClosePrice>161.64</ClosePrice>
        <Volume>2866237</Volume>
        <PriceCurrencyId>xxx</PriceCurrencyId>
        <PreviousTradingDate>2016-09-07</PreviousTradingDate>
        <PreviousClosePrice>160.35</PreviousClosePrice>
    </EODPriceSnapshotEntity>
</EODPriceSnapshots>

xsd file:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://api.company.com/">
    <xs:element name="EODPriceSnapshots">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="MessageInfo">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element type="xs:short" name="MessageCode"/>
                            <xs:element type="xs:string" name="MessageDetail"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
                <xs:element name="GeneralInfo">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element type="xs:string" name="ShareClassId"/>
                            <xs:element type="xs:string" name="CompanyName"/>
                            <xs:element type="xs:string" name="ExchangeId"/>
                            <xs:element type="xs:string" name="Symbol"/>
                            <xs:element type="xs:int" name="CUSIP"/>
                            <xs:element type="xs:int" name="CIK"/>
                            <xs:element type="xs:string" name="ISIN"/>
                            <xs:element type="xs:int" name="SEDOL"/>
                            <xs:element type="xs:string" name="CountryId"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
                <xs:element name="EODPriceSnapshotEntity">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element type="xs:date" name="TradingDate"/>
                            <xs:element type="xs:float" name="OpenPrice"/>
                            <xs:element type="xs:float" name="HighPrice"/>
                            <xs:element type="xs:short" name="LowPrice"/>
                            <xs:element type="xs:float" name="ClosePrice"/>
                            <xs:element type="xs:int" name="Volume"/>
                            <xs:element type="xs:string" name="PriceCurrencyId"/>
                            <xs:element type="xs:date" name="PreviousTradingDate"/>
                            <xs:element type="xs:float" name="PreviousClosePrice"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

Validate the xml schema

package CommonTool;  
import java.io.ByteArrayInputStream;  
import java.io.File;  
import java.io.InputStream;  

import javax.xml.transform.Source;  
import javax.xml.transform.stream.StreamSource;  
import javax.xml.validation.Schema;  
import javax.xml.validation.SchemaFactory;  
import javax.xml.validation.Validator;  

import org.apache.log4j.Logger;  
import org.xml.sax.SAXException;  

/** 
 * @desc    xml验证 
 * @author  copy 
 * @date    2016-09-08
 * 
 */  
public class XmlValidateUtil {  

    private static final Logger logger = Logger.getLogger(XmlValidateUtil.class);  

    private static final String SCHEMALANG = "http://www.w3.org/2001/XMLSchema";  

    /** 
     * Schema校验xml文件 
     * @param xmlPath xml字符串 
     * @param xsdPath xsd文件路径 
     * @return xml文件是否符合xsd定义的规则 
     */  
    public static boolean xmlStringValidate(String xmlStr, String xsdPath) {  
        boolean flag = false;  
        try {  
            SchemaFactory factory = SchemaFactory.newInstance(SCHEMALANG);  
            File schemaLocation = new File(xsdPath);  
            Schema schema = factory.newSchema(schemaLocation);  
            Validator validator = schema.newValidator();  
            InputStream is = new ByteArrayInputStream(xmlStr.getBytes());  
            Source source = new StreamSource(is);  
            try {  
                validator.validate(source);  
                flag = true;  
            } catch (SAXException ex) {  
                logger.info(ex.getMessage());  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return flag;  
    }  

    /** 
     * Schema校验xml文件 
     * @param xmlPath xml文件路径 
     * @param xsdPath xsd文件路径 
     * @return xml文件是否符合xsd定义的规则 
     */  
    public static boolean xmlFileValidate(String xmlPath, String xsdPath) {  
        boolean flag = false;  
        try {  
            SchemaFactory factory = SchemaFactory.newInstance(SCHEMALANG);  
            File schemaLocation = new File(xsdPath);  
            Schema schema = factory.newSchema(schemaLocation);  
            Validator validator = schema.newValidator();  
            Source source = new StreamSource(xmlPath);  

            try {  
                validator.validate(source);  
                flag = true;  
            } catch (SAXException ex) {  
                logger.info(ex.getMessage());  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return flag;  
    }  


    public static void main(String[] args) {
        String xmlPath = "D:\\workspace\\groovyStudy\\data\\xmlExample.xml";
        String xsdPath = "D:\\workspace\\groovyStudy\\data\\xsdExample.xsd";
        System.out.println("Test result is: " + xmlFileValidate(xmlPath, xsdPath));
    }
}  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值