使用命名空间将字符串解析为 org.w3c.dom.Document
Parsing String to org.w3c.dom.Document with namespaces
如何从包含 XML 的字符串创建文档?
我试过下面的代码,但是 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();
}
根据文档,
NodeList getElementsByTagNameNS(String namespaceURI, String localName)
以下将起作用,
System.out.println(document.getElementsByTagNameNS("http://schemas.xmlsoap.org/soap/envelope/", "Envelope").getLength());
如何从包含 XML 的字符串创建文档?
我试过下面的代码,但是 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();
}
根据文档,
NodeList getElementsByTagNameNS(String namespaceURI, String localName)
以下将起作用,
System.out.println(document.getElementsByTagNameNS("http://schemas.xmlsoap.org/soap/envelope/", "Envelope").getLength());