为什么这段代码会抛出MalformedURLException?

时间:2017-03-07 14:54:32

标签: java xml-parsing xml-namespaces

我有以下代码段:

public class DOMTest {

    public static void main( String[] args )
            throws ParserConfigurationException, SAXException, IOException {
        String xml = "<D:propfind xmlns:D=\"DAV:\""
                + " xmlns:C=\"urn:ietf:params:xml:ns:carddav\">\n"
                + "  <D:prop>\n" + "    <D:displayname />\n"
                + "    <C:getctag />\n" + "  </D:prop>\n" + "</D:propfind>";
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware( true );
        DocumentBuilder builder = null;
        Document doc = null;
        builder = factory.newDocumentBuilder();
        System.out.println( "namespaceAware=" + builder.isNamespaceAware()
                + ", validating=" + builder.isValidating() );
        doc = builder.parse( xml );
    }
}

运行它会产生以下输出:

namespaceAware=true, validating=false
Exception in thread "main" java.net.MalformedURLException: no protocol:
<D:propfind xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:carddav
  <D:prop>
    <D:displayname />
    <C:getctag />
  </D:prop>
</D:propfind>
at java.net.URL.<init>(URL.java:593)
at java.net.URL.<init>(URL.java:490)
at java.net.URL.<init>(URL.java:439)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:620)
at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(XMLVersionDetector.java:148)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:805)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:770)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:243)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:339)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:177)
at com.lemcke.c.dav.card.DOMTest.main(DOMTest.java:31)

xml是CardDAV请求的标准示例。这是使用命名空间时的一些配置问题吗?

2 个答案:

答案 0 :(得分:2)

parse方法可以将InputStream作为参数或字符串,如果你给它一个字符串,它会尝试打开字符串的位置,在你的情况下,字符串就是内容。

以下是解决此问题的方法:

    doc = builder.parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));

您可以在此处找到更多信息: http://docs.oracle.com/javase/1.5.0/docs/api/javax/xml/parsers/DocumentBuilder.html

答案 1 :(得分:0)

这是我的代码片段,对我有用:

Document doc;
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = null;
dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(website);

String website包含正确的XML网址,例如:https://www.w3schools.com/xml/note.xml

如果你想直接使用String,你应该尝试:

InputSource inputStream = new InputSource(new StringReader(xml));
return builder.parse(inputStream);