2017-10-29 58 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