Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Need help for convert xml by xstream

 
Haulyn Jason
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, all:
I have an XML file, format as follow:
<actions>
<action>
<path>admin.do</path>
<type>0</path>
</action>

<action>
<path>memberProfile.do</path>
<type>0</path>
</action>

<action>
<path>memberAccount.do</path>
<type>1</path>
</action>
</actions>


I want to convert to my javabean, and bind <action> node as Map, I mean <path> node value is the key and <type>node value is the value for HashMap<String,Long>();

Can anyone help me? and, if xstream is not suitable, other way is ok. I just need to convert the xml to a map. If it is necessary, I can change the format of xml.

Thanks!
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<?xml version="1.0" encoding="UTF-8"?>
<actions>
<action>
<path>admin.do</path>
<type>0</type>
</action>
<action>
<path>memberProfile.do</path>
<type>0</type>
</action>
<action>
<path>memberAccount.do</path>
<type>1</type>
</action>
</actions>
------------------------------------------------------------------------------------------------------------------------------------------------------

package pullparser;

import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

public class ActionMapper {

/**
* @param args
*/
public static void main(String[] args) {
XmlPullParserFactory factory=null;
Map<String,Long> aMap = new HashMap<String,Long>();
try {
factory = XmlPullParserFactory.newInstance();
} catch (XmlPullParserException e) {
e.printStackTrace();
}

FileReader fr = null;
XmlPullParser parser=null;
try {
fr=new FileReader("c:\\actions.xml");
parser = factory.newPullParser();
parser.setInput(fr);
int eventType =0;
eventType = parser.getEventType();
String tagName="";
String path="";
String type="";
while(eventType!=XmlPullParser.END_DOCUMENT) {
if(eventType==XmlPullParser.START_TAG) {
tagName = parser.getName();
}else if(eventType==XmlPullParser.TEXT) {
if(parser.getText().trim().length()==0){

}else if(tagName.equals("path")) {
path =parser.getText();
}else if(tagName.equals("type")) {
type = parser.getText();
aMap.put(path, new Long(type));
}
}
eventType = parser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}
System.out.println(aMap);
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic