2017-08-01 10 views
0

巨大なデータを含むXMLファイルがあります。私は、xmlファイルを解析され、JSONオブジェクトに値を追加しようとしているが、唯一の最後の値がadded.Pleaseは以下の私のコード見つけてきているしている:JSONオブジェクトに最後の値だけが追加されています。オブジェクト

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個のオブジェクト

を持つようになっている

{ 

"Virtualmemory":"1100320.000000", 
"cpuUsage":"0.000000", 
"process":"carkitd", 
"realmemory":"1044.000000", 
"thread":"2.000000", 
"cputime":"0.000000" 
} 

期待される結果

サンプルXMLファイル:

<instrument> 
    <slice time ='1498215480919'> 
     <process> 
      <processId>1.000000</processId> 
      <processName>launchd</processName> 
      <cpuUsage>0.203195</cpuUsage> 
      <realmemory>5084.000000</realmemory> 
      <Virtualmemory>1080112.000000</Virtualmemory> 
      <thread>7.000000</thread> 
      <cputime>0.000000</cputime> 
     </process> 
     <process> 
      <processId>24.000000</processId> 
      <processName>carkitd</processName> 
      <cpuUsage>0.002845</cpuUsage> 
      <realmemory>576.000000</realmemory> 
      <Virtualmemory>1074752.000000</Virtualmemory> 
      <thread>6.000000</thread> 
      <cputime>0.000000</cputime> 
     </process> 
     <process> 
      <processId>24.000000</processId> 
      <processName>carkitd</processName> 
      <cpuUsage>0.002845</cpuUsage> 
      <realmemory>576.000000</realmemory> 
      <Virtualmemory>1074752.000000</Virtualmemory> 
      <thread>6.000000</thread> 
      <cputime>0.000000</cputime> 
     </process> 
    </slice> 
    </instrument> 

私は何かを逃していますか?あなたが書いている

+0

forループの中にオブジェクトを作成し、オブジェクトがいっぱいになるとオブジェクトを配列に追加することによってJSONObjectの 'JSONArray'を使用します –

答えて

0

をJSONを初期化します。

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); 
0

Map tlike

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)); 

強行し、それが既に存在しているなら、これは値を上書きします。繰り返しごとに、JSONオブジェクトをオーバーライドするだけです。

すべての繰り返しで新しいJSONObjectを作成し、JSONArrayに保存する必要があります。

0

私の質問hereを参考にして簡単に実装できます。

JSON-javaライブラリはstlearyで使用できます。

次のコードを使用して、XML文字列をJSONObjectに変換できます。

JSONObject data = XML.toJSONObject(xmlString);

あなたがここでそれについての詳細情報を見つけることができます:上記参照してJSON-java

を、私はこれは同様に他の人のために働くことを願っていますleast.Iでソリューションを実装することができています。あなたのケースでは

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; 
} 

だけJSONArrayを作成し、ループ内であなたのJSONObjectを挿入しておくループ内

json = new JSONObject(); 
関連する問題