user1552545
user1552545

Reputation: 1331

Parsing String to org.w3c.dom.Document with namespaces

How can I create Document from a String containing XML?

I've tried the following code, but the document.getElementsByTagNameNS("Envelope", "http://schemas.xmlsoap.org/soap/envelope/") function call does not find any XML element.

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();
}

Upvotes: 0

Views: 1218

Answers (1)

lsiva
lsiva

Reputation: 485

As per documentaion,

NodeList getElementsByTagNameNS(String namespaceURI, String localName)

The below will work,

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

Upvotes: 2

Related Questions