我有以下 XML 代码:
<CampaignFrameResponse
xmlns="http://Qsurv/api"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Message>Success</Message>
<Status>Success</Status>
<FrameHeight>308</FrameHeight>
<FrameUrl>http://delivery.usurv.com?Key=a5018c85-222a-4444-a0ca-b85c42f3757d&ReturnUrl=http%3a%2f%2flocalhost%3a8080%2feveningstar%2fhome</FrameUrl>
</CampaignFrameResponse>
我想要做的是提取节点并将它们分配给一个变量。例如,我有一个名为FrameHeight
包含 value的变量308
。
这是我到目前为止的Java代码:
private void processNode(Node node) {
NodeList nodeList = node.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node currentNode = nodeList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
//calls this method for all the children which is Element
LOG.warning("current node name: " + currentNode.getNodeName());
LOG.warning("current node type: " + currentNode.getNodeType());
LOG.warning("current node value: " + currentNode.getNodeValue());
processNode(currentNode);
}
}
}
这会打印出节点名称、类型和值,但是将每个值分配给适当命名的变量的最佳方法是什么?例如int FrameHeight = 308
?
这是我更新的代码,其中 nodeValue 变量不断返回 null:
processNode(Node node) {
NodeList nodeList = node.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node currentNode = nodeList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
//calls this method for all the children which is Element
String nodeName = currentNode.getNodeName();
String nodeValue = currentNode.getNodeValue();
if(nodeName.equals("Message")) {
LOG.warning("nodeName: " + nodeName);
message = nodeValue;
LOG.warning("Message: " + message);
}
else if(nodeName.equals("FrameHeight")) {
LOG.warning("nodeName: " + nodeName);
frameHeight = nodeValue;
LOG.warning("frameHeight: " + frameHeight);
}
processNode(currentNode);
}
}
}