java.net.MalformedURLException: no protocol

前端 未结 2 891
野性不改
野性不改 2020-11-30 17:57

I am getting Java exception like:

java.net.MalformedURLException: no protocol

My program is trying to parse an XML string by using:

<
相关标签:
2条回答
  • 2020-11-30 18:40

    The documentation could help you : http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilder.html

    The method DocumentBuilder.parse(String) takes a URI and tries to open it. If you want to directly give the content, you have to give it an InputStream or Reader, for example a StringReader. ... Welcome to the Java standard levels of indirections !

    Basically :

    DocumentBuilder db = ...;
    String xml = ...;
    db.parse(new InputSource(new StringReader(xml)));
    

    Note that if you read your XML from a file, you can directly give the File object to DocumentBuilder.parse() .

    As a side note, this is a pattern you will encounter a lot in Java. Usually, most API work with Streams more than with Strings. Using Streams means that potentially not all the content has to be loaded in memory at the same time, which can be a great idea !

    0 讨论(0)
  • 2020-11-30 18:41

    Try instead of db.parse(xml):

    Document doc = db.parse(new InputSource(new StringReader(**xml**)));
    
    0 讨论(0)
提交回复
热议问题