Java.net.MalformedURLException: 没有协议。

216

我遇到了Java异常:

java.net.MalformedURLException: no protocol

我的程序尝试使用以下代码解析XML字符串:

Document dom;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.parse(xml);
XML字符串包含:
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"+
    "   <s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">"+
    "       <s:Header>"+
    "           <ActivityId CorrelationId=\"15424263-3c01-4709-bec3-740d1ab15a38\" xmlns=\"http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics\">50d69ff9-8cf3-4c20-afe5-63a9047348ad</ActivityId>"+
    "           <clalLog_CorrelationId xmlns=\"http://clalbit.co.il/clallog\">eb791540-ad6d-48a3-914d-d74f57d88179</clalLog_CorrelationId>"+
    "       </s:Header>"+
    "       <s:Body>"+
    "           <ValidatePwdAndIPResponse xmlns=\"http://tempuri.org/\">"+
    "           <ValidatePwdAndIPResult xmlns:a=\"http://schemas.datacontract.org/2004/07/ClalBit.ClalnetMediator.Contracts\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">"+
    "           <a:ErrorMessage>Valid User</a:ErrorMessage>"+
    "           <a:FullErrorMessage i:nil=\"true\" />"+
    "           <a:IsSuccess>true</a:IsSuccess>"+
    "           <a:SecurityToken>999993_310661843</a:SecurityToken>"+
    "           </ValidatePwdAndIPResult>"+
    "           </ValidatePwdAndIPResponse>"+
    "       </s:Body>\n"+
    "   </s:Envelope>\n";

有什么关于导致这个错误的建议吗?


你到底在哪里收到了那个错误信息?是在解析XML时还是在尝试通过网络发送时?如果在解析时出现这种情况,那就真的很奇怪了。 - Jesper
请问是否重复?https://dev59.com/0Oo6XIcBkEYKwwoYTzJK#964377 - Fernando Gonzalez Sanchez
2个回答

444

这份文档可能会对您有所帮助:http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilder.html

方法DocumentBuilder.parse(String)需要一个URI并尝试打开它。如果您想直接提供内容,则必须提供InputStreamReader,例如StringReader。 ... 欢迎来到Java标准级别的间接性!

基本上:

DocumentBuilder db = ...;
String xml = ...;
db.parse(new InputSource(new StringReader(xml)));
请注意,如果您从文件中读取XML,则可以直接将File对象提供给DocumentBuilder.parse()
顺便说一下,在Java中,您会经常遇到这种模式。通常,大多数API使用流而不是字符串进行操作。使用流意味着潜在地不需要同时将所有内容加载到内存中,这可能是一个好主意!

4
@Guillaume,我这样做会得到document = null。为什么会发生这种情况? - HenioJR
1
没有代码的情况下无法确定。也许您的输入无效,而且您不小心吞掉了异常... - Guillaume
1
+1 是我愚蠢地假设字符串参数应该是要解析的 XML.... 当然,期望一个 URI 也是非常合理的.... - Nicholas Terry
@RajShah 你应该只在启动时运行这个逻辑,因此更长的时间消耗不应该有影响。你也不应该经常改变配置... - Nicholas Terry
打印出的文档为[#document: null],但是document.getDocumentElement()返回了预期的XML。 - user2521119
显示剩余2条评论

29

尝试使用db.parse(xml)代替:

Document doc = db.parse(new InputSource(new StringReader(**xml**)));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接