我收到 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";
关于导致此错误的原因有什么建议吗?
最佳答案
文档可以帮助您:http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilder.html
DocumentBuilder.parse(String)
方法接受一个 URI 并尝试打开它。如果你想直接给内容,你必须给它一个InputStream
或Reader
,例如一个StringReader
。 ...欢迎使用 Java 标准的间接级别!
基本上:
DocumentBuilder db = ...;
String xml = ...;
db.parse(new InputSource(new StringReader(xml)));
请注意,如果您从文件中读取 XML,您可以直接将 File
对象赋予 DocumentBuilder.parse()
。
附带说明,这是您在 Java 中会经常遇到的一种模式。通常,大多数 API 使用 Streams 比使用 Strings 更多。使用 Streams 意味着可能不必同时将所有内容加载到内存中,这可能是个好主意!
关于java.net.MalformedURLException : no protocol,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1706493/