java.net.MalformedURLException:无协议

我得到了如下Java异常:

java.net.MalformedURLException:无协议

我的程序正在尝试使用以下方法解析XML字符串:

文档dom;
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
dom=db.parse(xml);

XML字符串包含:

stringxml=“<?xml版本=\'1.0\'编码=\'utf-8\'?>”+
“<s:Envelope xmlns:s=\”http://schemas.xmlsoap.org/soap/envelope/\“>”+
“<s:标题>”+
“<ActivityId CorrelationId=\”15424263-3c01-4709-bec3-740d1ab15a38\”xmlns=\”http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics\“>50d69ff9-8cf3-4c20-afe5-63a9047348ad</ActivityId>”+
“<clalLog\u CorrelationId xmlns=\”http://clalbit.co.il/clallog\“>eb791540-ad6d-48a3-914d-d74f57d88179</clalLog_CorrelationId>”+
“</s:Header>”+
“<s:Body>”+
“<validatePWandipResponse xmlns=\”http://tempuri.org/\“>”+
“<ValidatePwdandPresult xmlns:a=\”http://schemas.datacontract.org/2004/07/ClalBit.ClalnetMediator.Contracts\“xmlns:i=\”http://www.w3.org/2001/XMLSchema-instance\“>”+
“<a:ErrorMessage>有效用户</a:ErrorMessage>”+
“<a:i:nil=\'true\'/>”+
“<a:IsSuccess>true</a:IsSuccess>”+
“<a:SecurityToken>99993</a:SecurityToken>”+
“</validatePwdandPreslt>”+
“</validatePWandipResponse>”+
“</s:Body>\n”+
“</s:Envelope>\n”;

关于导致此错误的原因有何建议

文档可以帮助您:http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilder.html

方法DocumentBuilder.parse(String)获取URI并尝试打开它。如果要直接提供内容,则必须为其提供一个InputStreamReader,例如StringReader。。。欢迎使用Java标准级别的间接寻址

基本上:

DocumentBuilderDB=。。。;
字符串xml=。。。;
parse(新的InputSource(新的StringReader(xml));

请注意,如果从文件中读取XML,可以直接将文件对象提供给DocumentBuilder.parse()

作为旁注,这是您在Java中经常遇到的一种模式。通常,大多数API更多地使用流而不是字符串。使用流意味着可能并非所有内容都必须同时加载到内存中,这是一个好主意

发表评论