4

我正在尝试编写一个单元测试,它将针对 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)
4

1 回答 1

12

问题是代码中的这一行:

Source xmlFile = new StreamSource(xmlDoc);

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

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

Source xmlFile = new StreamSource(new StringReader(xmlDoc));
于 2013-09-05T18:01:36.010 回答