gpt4 book ai didi

java - 从 XML 检索数据

转载 作者:行者123 更新时间:2023-11-30 07:58:58 25 4
gpt4 key购买 nike

我有一个 SOAP 网络服务,它返回给定的响应:

<soap:Envelope xmlns:soap="">
<soap:Body>
<ns2:getRegisterValuesResponse xmlns:ns2="">
<return>
<id>11931</id>
<value>0</value>
</return>
<return>
<id>11946</id>
<value>0</value>
</return>
<return>
<id>11961</id>
<value>0</value>
</return>
</ns2:getRegisterValuesResponse>
</soap:Body>
</soap:Envelope>

如何在 java 方法中检索给定的整数?

这是我的方法。这个想法是使用给定的 id 和值每 X 分钟更新一次数据库。

public class RegisterLog implements Job {

public void execute(final JobExecutionContext ctx)
throws JobExecutionException {
SimulatorSOAPClientSAAJ sc=new SimulatorSOAPClientSAAJ();
SOAPMessage msg = sc.sOAPConnect();
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
msg.writeTo(out);
} catch (SOAPException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String strMsg = new String(out.toByteArray());
System.out.println(strMsg);

最佳答案

使用 DOM XML 解析器 http://www.w3schools.com/dom/default.asp

导入

import java.io.ByteArrayInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.*;

代码

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
ByteArrayInputStream bais = new ByteArrayInputStream(out.toByteArray());
Document doc = dBuilder.parse(bais);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("return");
for (int i=0;i<nList.getLength();i++) {
Node nNode = nList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element curElement = (Element) nNode;
int id = Integer.parseInt(curElement.getElementsByTagName("id").item(0).getTextContent());
String value = curElement.getElementsByTagName("value").item(0).getTextContent();
}
}

关于java - 从 XML 检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32225410/

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