gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:40:20 24 4
gpt4 key购买 nike

如何从包含 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());

关于java - 使用命名空间将字符串解析为 org.w3c.dom.Document,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38509774/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com