一、java源码
三、json结果
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class xml2json
{
public static void main(String[] arge)throws ParserConfigurationException, SAXException, IOException
{
File f = new File("D:\\321.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(f);
NodeList nl = doc.getElementsByTagName("city");
StringBuffer res = new StringBuffer();
res.append("{\"maps\":{\"version\":[");
for (int i = 0; i < nl.getLength(); i++) {
String name = doc.getElementsByTagName("name").item(i).getFirstChild()
.getNodeValue();
String pinyin = doc.getElementsByTagName("pinyin").item(i)
.getFirstChild().getNodeValue();
String durl = doc.getElementsByTagName("durl").item(i).getFirstChild()
.getNodeValue();
String size = doc.getElementsByTagName("size").item(i).getFirstChild()
.getNodeValue();
if (i == nl.getLength() - 1)
res.append("{\"name\":\"" + name + "\",\"pinyin\":\"" + pinyin + "\",\"durl\":\"" + durl + "\",\"size\":\"" + size + "\"}");
else {
res.append("{\"name\":\"" + name + "\",\"pinyin\":\"" + pinyin + "\",\"durl\":\"" + durl + "\",\"size\":\"" + size + "\"},");
}
}
res.append("]}}");
System.out.println(res);
}
}
二、xml文件
<?xml version="1.0" encoding="UTF-8"?>
<maps>
<version>
<city code="010">
<name>北京</name>
<pinyin>BeiJing</pinyin>
<durl>http://114.247.50.22:8081/mapdown/citys/BeiJing.zip</durl>
<size>24736893</size>
</city>
<city code="021">
<name>上海</name>
<pinyin>ShangHai</pinyin>
<durl>http://114.247.50.22:8081/mapdown/citys/ShangHai.zip</durl>
<size>42637020</size>
</city>
</version>
</maps>
三、json结果
{"maps":{"version":[{"name":"北京","pinyin":"BeiJing","durl":"http://114.247.50.
22:8081/mapdown/citys/BeiJing.zip","size":"24736893"},
{"name":"上海","pinyin":"ShangHai","durl":"http://114.247.50.
22:8081/mapdown/citys/ShangHai.zip","size":"42637020"}
]
}
}