我有一个包含大量数据的xml文件。我已经解析了xml文件,并尝试将值添加到JSON对象,但只添加了最后一个值。请在下面找到我的代码:
use App\Article;
class ArticlesTableSeeder extends Seeder
{
public function run()
{
// Let's truncate our existing records to start from scratch.
Article::truncate();
$faker = \Faker\Factory::create();
// And now, let's create a few articles in our database:
for ($i = 0; $i < 50; $i++) {
Article::create([
'title' => $faker->sentence,
'body' => $faker->paragraph,
]);
}
}
}
当我运行上面的代码时,我得到以下结果
实际结果:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Process_Parser {
static JSONObject json= new JSONObject();
//static //JSONObject arrayvalue=new JSONArray();
public static void main(String args[]) {
try {
File process = new File("/Users/instrument.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(process);
doc.getDocumentElement().normalize();
//System.out.println("root of xml file" + doc.getDocumentElement().getNodeName());
NodeList nodes = doc.getElementsByTagName("process");
//System.out.println("==========================");
Element pageElement = (Element)doc.getElementsByTagName("process").item(0);
//NodeList result = pageElement.getElementsByTagName("processName");
System.out.println("Suba-----------"+nodes.getLength());
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
//System.out.println(getValue("processName", element).contains("carkitd"));
//if(element.getElementsByTagName("process") != null){
if(element.getFirstChild().getNodeValue() != null){
if(getValue("processName", element).contains("carkitd")){
json.put("processName",getValue("processName", element));
json.put("cpuUsage",getValue("cpuUsage", element));
json.put("realmemory",getValue("realmemory", element));
json.put("Virtualmemory",getValue("Virtualmemory", element));
json.put("thread",getValue("thread", element));
json.put("cputime",getValue("cputime", element));
}
}
}
}
//System.out.println("result-array:" +arrayvalue);
System.out.println("result" +json);
//}
//System.out.println("arrayvalue::"+arrayvalue.size());
}catch (Exception ex) {
ex.printStackTrace();
}
}
private static String getValue(String tag, Element element) {
NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodes.item(0);
return node.getNodeValue();
}
}
预期结果:
它应该有67个对象
示例xml文件:
{
"Virtualmemory":"1100320.000000",
"cpuUsage":"0.000000",
"process":"carkitd",
"realmemory":"1044.000000",
"thread":"2.000000",
"cputime":"0.000000"
}
我错过了什么吗?
答案 0 :(得分:1)
创建JSONArray
并继续将JSONObject
插入循环中。
JSONArray finalArray = new JSONArray(); // create your jsonarray
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
//System.out.println(getValue("processName", element).contains("carkitd"));
//if(element.getElementsByTagName("process") != null){
if (element.getFirstChild().getNodeValue() != null) {
if (getValue("processName", element).contains("carkitd")) {
JSONObject json = new JSONObject(); // your temp obj
json.put("processName", getValue("processName", element));
json.put("cpuUsage", getValue("cpuUsage", element));
json.put("realmemory", getValue("realmemory", element));
json.put("Virtualmemory", getValue("Virtualmemory", element));
json.put("thread", getValue("thread", element));
json.put("cputime", getValue("cputime", element));
finalArray.put(json); // push your values in the array
}
}
}
}
//System.out.println("result-array:" +arrayvalue);
System.out.println("result " + finalArray);
答案 1 :(得分:0)
你在写:
json.put("processName",getValue("processName", element));
json.put("cpuUsage",getValue("cpuUsage", element));
json.put("realmemory",getValue("realmemory", element));
json.put("Virtualmemory",getValue("Virtualmemory", element));
json.put("thread",getValue("thread", element));
json.put("cputime",getValue("cputime", element));
Jus tlike a Map
,如果它已经存在,则覆盖该值。在每次迭代中,您只需覆盖您的JSON对象。
您应该在每次迭代时创建一个新的JSONObject
并将其存储在JSONArray
中。
答案 2 :(得分:0)
您可以参考我的问题here以便更轻松地实施。
您可以通过stleary使用JSON-java库。
您可以使用以下代码将XML字符串转换为JSONObject。
JSONObject data = XML.toJSONObject(xmlString);
您可以在此处找到有关它的更多信息:JSON-java
通过上述参考,我至少可以实现解决方案。我希望这也适用于其他人。
private static JSONObject extractData(NodeList nodeList, String tagName) throws TransformerConfigurationException,
TransformerException, TransformerFactoryConfigurationError, JSONException {
JSONObject resultObject = new JSONObject();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (!node.getNodeName().equals(tagName) && node.hasChildNodes()) {
return extractData(node.getChildNodes(), tagName);
} else if (node.getNodeName().equals(tagName)) {
DOMSource source = new DOMSource(node);
StringWriter stringResult = new StringWriter();
TransformerFactory.newInstance().newTransformer().transform(source, new StreamResult(stringResult));
resultObject = XML.toJSONObject(stringResult.toString()).optJSONObject(tagName);
}
}
return resultObject;
}
public static JSONObject getFullData(String tagName, SOAPMessage message) throws Exception {
NodeList nodeList = message.getSOAPBody().getChildNodes();
JSONObject resultObject = extractData(nodeList, tagName);
return resultObject;
}
对于你的情况,只需在循环中初始化json
json = new JSONObject();