简体   繁体   English

使用名称空间将字符串解析为org.w3c.dom.Document

[英]Parsing String to org.w3c.dom.Document with namespaces

How can I create Document from a String containing XML? 如何从包含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. 我已经尝试了以下代码,但是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();
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM