XML字符串和XML DOCUMENT的相互转换

在做一般的XML数据交换过程中,我更乐意传递XML字符串,而不是格式化的XML Document。这就涉及到XML字符串和Xml Document的转换问题,说白了这是个很简单的问题,本文就各种XML解析器分别列举如下,以方便自己今后查阅。
  一、使用最原始的javax.xml.parsers,标准的jdk api
  // 字符串转XML
  String xmlStr = "......";
  StringReader sr = new StringReader(xmlStr);
  InputSource is = new InputSource(sr);
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder=factory.newDocumentBuilder();
  Document doc = builder.parse(is);
  //XML转字符串
  TransformerFactory tf = TransformerFactory.newInstance();
  Transformer t = tf.newTransformer();
  t.setOutputProperty("encoding","GB23121");//解决中文问题,试过用GBK不行
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  t.transform(new DOMSource(doc), new StreamResult(bos));
  String xmlStr = bos.toString();
  这里的XML DOCUMENT为org.w3c.dom.Document
  二、使用dom4j后程序变得更简单
  // 字符串转XML
  String xmlStr = "......";
  Document document = DocumentHelper.parseText(xmlStr);
  // XML转字符串
  Document document = ...;
  String text = document.asXML();
  这里的XML DOCUMENT为org.dom4j.Document
  三、使用JDOM
  JDOM的处理方式和第一种方法处理非常类似
  //字符串转XML
  String xmlStr = ".....";
  StringReader sr = new StringReader(xmlStr);
  InputSource is = new InputSource(sr);
  Document doc = (new SAXBuilder()).build(is);
  //XML转字符串
  Format format = Format.getPrettyFormat();
  format.setEncoding("gb2312");//设置xml文件的字符为gb2312,解决中文问题
  XMLOutputter xmlout = new XMLOutputter(format);
  ByteArrayOutputStream bo = new ByteArrayOutputStream();
  xmlout.output(doc,bo);
  String xmlStr = bo.toString();
  这里的XML DOCUMENT为org.jdom.Document
  四、JAVASCRIPT中的处理
  //字符串转XML
  var xmlStr = ".....";
  var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async=false;
  xmlDoc.loadXML(xmlStr);
  //可以处理这个xmlDoc了
  var name = xmlDoc.selectSingleNode("/person/name");
  alert(name.text);
  //XML转字符串
  var xmlDoc = ......;
  var xmlStr = xmlDoc.xml
  这里的XML DOCUMENT为javascript版的XMLDOM 

Java中,可以使用多种方式将XML字符串转换成JSON字符串,或将JSON字符串转换XML字符串。以下是一些常用的方法: 1. 使用第三方库 常用的XML和JSON转换库有:jackson、Gson、xmlpull、xmlbeans、dom4j、jdom等。这些库提供了各种将XML和JSON字符串互相转换的方法。例如,使用Jackson库将XML字符串转换为JSON字符串: ```java import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; String xmlString = "<person><name>John</name><age>30</age></person>"; // 将XML字符串转换为Java对象 XmlMapper xmlMapper = new XmlMapper(); Object obj = xmlMapper.readValue(xmlString, Object.class); // 将Java对象转换为JSON字符串 ObjectMapper jsonMapper = new ObjectMapper(); String jsonString = jsonMapper.writeValueAsString(obj); System.out.println(jsonString); ``` 输出结果为: ```json {"person":{"name":"John","age":"30"}} ``` 2. 手动转换 也可以手动编写代码将XML和JSON字符串互相转换。例如,使用Java内置的XML DOM APIXML字符串转换为JSON字符串: ```java import org.json.JSONObject; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.util.HashMap; import java.util.Map; String xmlString = "<person><name>John</name><age>30</age></person>"; // 将XML字符串解析为DOM对象 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(xmlString))); // 将DOM对象转换为JSON对象 JSONObject json = new JSONObject(); Element root = doc.getDocumentElement(); if (root.hasChildNodes()) { NodeList nodeList = root.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; Map<String, String> map = new HashMap<>(); if (element.hasAttributes()) { for (int j = 0; j < element.getAttributes().getLength(); j++) { map.put(element.getAttributes().item(j).getNodeName(), element.getAttributes().item(j).getNodeValue()); } } if (element.hasChildNodes()) { json.put(element.getNodeName(), element.getTextContent()); } else if (!map.isEmpty()) { json.put(element.getNodeName(), new JSONObject(map)); } } } } System.out.println(json.toString()); ``` 输出结果为: ```json {"person":{"name":"John","age":"30"}} ``` 3. 使用XPath表达式 我们还可以使用XPath表达式从XML中提取数据,并将其转换为JSON格式。例如,使用Java内置的XPath APIXML字符串转换为JSON字符串: ```java import org.json.JSONObject; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import java.io.StringReader; String xmlString = "<person><name>John</name><age>30</age></person>"; // 创建XPath对象 XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); // 编译XPath表达式 XPathExpression expr = xpath.compile("/*"); // 将XML字符串解析为DOM对象 InputSource source = new InputSource(new StringReader(xmlString)); NodeList nodes = (NodeList) expr.evaluate(source, XPathConstants.NODESET); // 将DOM对象转换为JSON对象 JSONObject json = new JSONObject(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; if (element.hasChildNodes()) { json.put(element.getNodeName(), element.getTextContent()); } } } System.out.println(json.toString()); ``` 输出结果为: ```json {"person":{"name":"John","age":"30"}} ``` 注意:以上示例仅供参考,实际使用时需要根据具体情况进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值