把Json转Xml并且用xpath读取xml元素(JAVA)

maven

<dependency>  
    <groupId>net.sf.json-lib</groupId>  
    <artifactId>json-lib</artifactId>  
    <version>2.4</version>  
    <classifier>jdk15</classifier>  
</dependency>  
<dependency>
    <groupId>xom</groupId>
    <artifactId>xom</artifactId>
    <version>1.2.5</version>
</dependency>

操作代码

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.dom4j.DocumentException;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;

public class Test {
    public static String json2Xml(String json) {
        try {
            JSONObject jo = JSONObject.fromObject(json);
            XMLSerializer serializer = new XMLSerializer();
            return serializer.write(jo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws FileNotFoundException, SAXException, IOException,
            ParserConfigurationException, DocumentException, XPathExpressionException {
        String str = "{\"avg\":\"432432\",\"interview\":{\"m\":{\"uv\":321321,\"pv\":432432}}}";
        str = json2Xml(str);
        System.out.println(str);
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = builder.parse(new InputSource(new StringReader(str)));
        XPath xpath = XPathFactory.newInstance().newXPath();
                System.out.println((String) xpath.evaluate("/o/interview/m/uv", document));
    }

}

注意事项:

由于平时我们命名的json的key名称有可能为数字开头的,例如
{"1h":31}
而xml规则中则不允许出现数字开头
如<123a>这样的标签是不合法的
所以一旦json字符串中出现以上的不合法命名则出现以下出错
nu.xom.IllegalNameException: NCNames cannot start with the character 31
    at nu.xom.Verifier.throwIllegalNameException(Unknown Source)
    at nu.xom.Verifier.checkNCName(Unknown Source)
    at nu.xom.Element._setLocalName(Unknown Source)
    at nu.xom.Element.<init>(Unknown Source)
    at nu.xom.Element.<init>(Unknown Source)
原创文章 54 获赞 168 访问量 63万+

猜你喜欢

转载自blog.csdn.net/bojie5744/article/details/51038239
今日推荐