使用命名空间将String解析为org.w3c.dom.Document

时间:2016-07-21 16:36:12

标签: java xml dom xml-namespaces

如何从包含XML的String创建Document?

我已尝试过以下代码,但 document.getElementsByTagNameNS(" Envelope"," http://schemas.xmlsoap.org/soap/envelope/") 函数调用找不到任何XML元素。

String xml = "<soapenv:Envelope\n" +
        "        xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
        "\t<soapenv:Header>\n" +
        "\t</soapenv:Header>\n" +
        "\t<soapenv:Body>\n" +
        "\t</soapenv:Body>\n" +
        "</soapenv:Envelope>";

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
    factory.setNamespaceAware(true);
    builder = factory.newDocumentBuilder();
    Document document = builder.parse(new InputSource(new StringReader(xml)));
    System.out.println(document.getElementsByTagNameNS("Envelope", "http://schemas.xmlsoap.org/soap/envelope/").getLength());
} catch (Exception e) {
    e.printStackTrace();
}

1 个答案:

答案 0 :(得分:1)

根据文件,

NodeList getElementsByTagNameNS(String namespaceURI, String localName)

以下内容可行,

System.out.println(document.getElementsByTagNameNS("http://schemas.xmlsoap.org/soap/envelope/", "Envelope").getLength());