2017-10-29 60 views
0

我看到这里一些例子,显示如何验证XML文件(It's workking),但我的问题是:如何修改这个代码来验证一个字符串如何验证java中的xml字符串?

import javax.xml.XMLConstants; 
import javax.xml.transform.Source; 
import javax.xml.transform.stream.StreamSource; 
import javax.xml.validation.*; 
import org.xml.sax.ErrorHandler; 
import org.xml.sax.SAXException; 
import org.xml.sax.SAXParseException; 
import java.util.List; 
import java.io.*; 
import java.util.LinkedList; 
import java.net.URL; 
import java.sql.Clob; 
import java.sql.SQLException; 
public class Validate { 

    public String validaXML(){ 

     try { 
     Source xmlFile = new StreamSource(new File("C:\\Users\\Desktop\\info.xml")); 
     URL schemaFile = new URL("https://www.w3.org/2001/XMLSchema.xsd"); 
     SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
     Schema schema = schemaFactory.newSchema(schemaFile); 
     Validator validator = schema.newValidator(); 
     final List exceptions = new LinkedList(); 
     validator.setErrorHandler(new ErrorHandler() 
      { 
      @Override 
      public void warning(SAXParseException exception) throws SAXException 
      { 
      exceptions.add(exception); 
      } 
      @Override 
      public void fatalError(SAXParseException exception) throws SAXException 
      { 
      exceptions.add(exception); 
      } 
      @Override 
      public void error(SAXParseException exception) throws SAXException 
      { 
      exceptions.add(exception); 
      } 
      }); 

     validator.validate(xmlFile); 

      } catch (SAXException ex) { 
       System.out.println(ex.getMessage()); 
       return ex.getMessage().toString(); 

      } catch (IOException e) { 
      System.out.println(e.getMessage()); 
      return e.getMessage().toString(); 
     } 
     return "Valid"; 
    } 

    public static void main(String[] args) { 
     String res; 
     Validate val = new Validate(); 
     res=val.validaXML(); 
     System.out.println(res); 
    } 
} 

我有试过这样的:

Source xmlFile = new StreamSource("<Project><Name>sample</Name></Project>"); 

它编译,但我得到了这一点:

“没有协议:样本”

感谢您的阅读我会认为您的意见

+0

这应该工作:'新的StreamSource(新StringReader( “_ your_string_here” ))' – Vasan

回答

1

该原因为什么无法正常工作是您使用的构造函数是StreamSource(String systemId)。 StreamSource上的String构造函数不接受xml。

使用构造StreamSource(Reader reader)并作出读者,如

new StreamSource(new StringReader("xml here")) 

,或者您可以使用构造StreamSource(InputStream inputStream)作为

new StreamSource(new ByteArrayInputStream("xml here".getBytes())) 
+0

你是绝对正确的,非常感谢! – Ernesto