麻烦验证XML对XSD(java)

时间:2013-09-05 17:49:00

标签: java xml xsd

我正在尝试编写一个单元测试,它将针对XSD验证XML字符串文档。请注意,XSD存储在磁盘上,用于XML文档中名称空间的URL实际上不能通过Web服务器获得。

以下是代码:

 @Test
public void testValidateAgainstXSD() throws Exception {
    String xmlDoc = MY_XML_DOC_SAMPLE;
    File schemaFile = new File("/Users/philswenson/dev/optimize_l/modules/ae/staging/eda-eventtypes/Analysis/1.0/MeasurementResultStatistics.xsd");

    Source xmlFile = new StreamSource(xmlDoc);
    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");
    } catch (SAXException e) {
        throw new RuntimeException(e);
    }
}

当我运行测试时,我收到以下错误。关于我做错了什么想法?

java.net.MalformedURLException: no protocol: <?xml version="1.0" encoding="utf-8"?>
<p:MeasurementResultStatistics xmlns:p="http://namespaces.myco.com/EDA/Analysis/1.0">  <p:Average>5.0</p:Average>
  <p:Minimum>0.1</p:Minimum>
  <p:Maximum>10.3</p:Maximum>
  <p:StandardDeviation>0.0</p:StandardDeviation>
  <p:HourOfDay>7</p:HourOfDay>
  <p:DayOfWeek>Mon</p:DayOfWeek>
<p2:MeasurementDefinition xmlns:p2="http://namespaces.myco.com/EDA/Analysis/1.0">
<p2:Name>TEST KPI NAME</p2:Name>
<p2:DisplayName>TEST DISPLAY NAME</p2:DisplayName>
<p2:Version>1</p2:Version>
<p2:MeasurementUnits>TEST UOM</p2:MeasurementUnits>
<p2:TimeInterval>10000</p2:TimeInterval>
</p2:MeasurementDefinition>
<p3:MeasurementMember xmlns:p3="http://namespaces.myco.com/EDA/Analysis/1.0">
<p3:Name>TEST MONITOR STRING ID</p3:Name>
<p3:DisplayName>TEST DISPLAY NAME</p3:DisplayName>
</p3:MeasurementMember>
</p:MeasurementResultStatistics>
    at java.net.URL.<init>(URL.java:567)
    at java.net.URL.<init>(URL.java:464)
    at java.net.URL.<init>(URL.java:413)
    at org.apache.xerces.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)
    at org.apache.xerces.impl.XMLVersionDetector.determineDocVersion(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.jaxp.validation.StreamValidatorHelper.validate(Unknown Source)
    at org.apache.xerces.jaxp.validation.ValidatorImpl.validate(Unknown Source)
    at javax.xml.validation.Validator.validate(Validator.java:127)
    at com.myco.optimize.monitor.engine.XSDValidatorTest.testValidateAgainstXSD(XSDValidatorTest.java:46)

1 个答案:

答案 0 :(得分:11)

问题在于代码中的这一行:

Source xmlFile = new StreamSource(xmlDoc);

正如我们在the documentation中看到的那样,StreamSource构造函数假定String参数是一个URL,而不是XML内容。因此,它试图将您的XML解释为它是一个URL,并且毫不奇怪,XML并不是以有效的协议(例如“http:”)开头。

解决方案是使用StreamSource(Reader)构造函数:

Source xmlFile = new StreamSource(new StringReader(xmlDoc));