转入java一段时间了,还没有用java处理过xml。正好非开发的同事有个xml需要处理,也顺便学习下
需求:将value属性的值全部换成name属性的值
jar包下载地址:
1.xmlpull_1_1_3_4c.jar 点击下载xmlpull
2.kxml2-2.3.0.jar 点击下载kxml2-2.3.0.jar
maven下载方式:
<dependency>
<groupId>xmlpull</groupId>
<artifactId>xmlpull</artifactId>
<version>1.1.3.1</version>
</dependency>
<dependency>
<groupId>kxml2</groupId>
<artifactId>kxml2</artifactId>
<version>2.3.0</version>
</dependency>
<?xml version="1.0" encoding="utf-8" ?>
<texts>
<text name="Individual" value="个人" ></text>
<text name="HomePage" value="首页" ></text>
<text name="Project" value="项目" ></text>
<text name="Document" value="文档" ></text>
</texts>
public static List<Text> getText(InputStream xml) throws Exception
{
List<Text> lst = null;
Text text = null;
// 获得pull解析器工厂
XmlPullParserFactory pullParserFactory = XmlPullParserFactory.newInstance();
//获取XmlPullParser的实例
XmlPullParser pullParser = pullParserFactory.newPullParser();
// 设置需要解析的XML数据
pullParser.setInput(xml, "UTF-8");
// 取得事件
int event = pullParser.getEventType();
// 若为解析到末尾
while (event != XmlPullParser.END_DOCUMENT) // 文档结束
{
String nodeName = pullParser.getName(); // 节点名称
switch (event)
{
case XmlPullParser.START_DOCUMENT: // 文档开始
lst = new ArrayList<Text>();
break;
case XmlPullParser.START_TAG: // 标签开始
if ("text".equals(nodeName))
{
text = new Text();
String name = pullParser.getAttributeValue(0);
String value = pullParser.getAttributeValue(1);
text.setName(name);
text.setValue(value);
}
break;
case XmlPullParser.END_TAG: // 标签结束
if ("text".equals(nodeName))
{
lst.add(text);
text = null;
}
break;
}
event = pullParser.next(); // 下一个标签
}
return lst;
}
public class Text {
private String name;
private String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
File xmlFile = new File("/Users/law/Downloads/中文版.xml");
FileInputStream inputStream = new FileInputStream(xmlFile);
List<Text> textList = getText(inputStream);