0

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

1 Answer 1

2

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());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.