java对象转换为xml文档,xml字符串转json字符串。

模型类

import java.util.List;
import java.util.Map;
/**
 * 	xml的java对象
 * 属性qname 标签名
 * 属性 value 标签值
 * 属性child 子节点集合
 * 属性 attribute 属性集合
 * */
public class XmlNode {
	// 标签名
	String qname;
	// 标签值
	String value;
	// 子集
	List<XmlNode> child;
	// 属性集合
	Map<String,String> attribute;
	public String getQname() {
		return qname;
	}
	public void setQname(String qname) {
		this.qname = qname;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}
	

	public List<XmlNode> getChild() {
		return child;
	}
	public void setChild(List<XmlNode> child) {
		this.child = child;
	}
	
	public Map<String, String> getAttribute() {
		return attribute;
	}
	public void setAttribute(Map<String, String> attribute) {
		this.attribute = attribute;
	}
	
	
}

工具类:

package com.toone.common.util.xml;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * @author renc
 * create by 2020/3/6
 * 作用:java对象与xml
 * 
 * */
public class XmlUtil {
	// 前缀
	private final static String PREFIX = "<";
	// 后缀
	private final static String SUFFIX=">";
	/**
	 *  xml字符串转换为xml的java节点对象
	 *  @param xml xml的字符串形如<root><node1></node></root>
	 *  这样的标准xml字符串
	 * */
	public  static XmlNode parseNode(String xml) throws ParserConfigurationException, SAXException, IOException{
		InputStream is = new ByteArrayInputStream(xml.getBytes());
		// Document文档对象
		Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
		return xmlAnalysis(doc); 
	}
	// 解析xml
	public static XmlNode xmlAnalysis(Document doc) throws ParserConfigurationException, SAXException, IOException{
		// 创建根节点xml对象
		XmlNode root = new XmlNode();
				// 根节点
				Element ele = doc.getDocumentElement();
				// 设置xml根节点标签名
				root.setQname(ele.getNodeName());
				// 读取文档根节点所有属性
				NamedNodeMap nameNodeMap=ele.getAttributes();
				// 获取属性集合长度
				int attLength= nameNodeMap.getLength();
				
				if(attLength>0){
					Map<String,String> map=new HashMap<String, String>();
					root.setAttribute(map);
					for (int j = 0; j < attLength; j++) {
						String key= nameNodeMap.item(j).getNodeName();
						String value=nameNodeMap.item(j).getNodeValue();
						map.put(key, value);
					}
				}
				// 创建子节点并获取值
			getChildsNode(ele, root);
		return root;
	}
	/**
	 * 转换xml文件到xml节点。
	 * @param  path xml文件路径
	 * */
	public static XmlNode parseNodeByFilePath(String path) throws SAXException, IOException, ParserConfigurationException,NullPointerException{
		File file=getFileByPath(path);
		if(!file.exists()){
			throw new NullPointerException("文件路径为空:"+path);
		}
		Document doc= DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
		return xmlAnalysis(doc);
	}
	// 创建文件
	private static File getFileByPath(String path){
		File file=new File(path);
		return file;
	}

	/**
	 * 转换为xml文件到xml节点
	 * @param  FileId 服务器文件Id
	 * */
	public static XmlNode parseNodeByFileId(String FileId) throws SAXException, IOException, ParserConfigurationException,NullPointerException{
		InputStream is=getFileById(FileId);
		if(is==null){
			throw new NullPointerException("参数:FileId为空");
		}
		Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
		return xmlAnalysis(doc);
		
	}
	// 递归当前节点
	private static void getChildsNode(Node father, XmlNode node) throws ParserConfigurationException, SAXException, IOException{
		if(node.getChild()==null){
			node.setChild(new ArrayList<XmlNode>());
		}
		// 当前父节点的所有子节点
		NodeList nodeList= father.getChildNodes();
		// 子节点集合长度
		int length=nodeList.getLength();
		for (int i = 0; i < length; i++) {
			Node node1=nodeList.item(i);
			if((node1.getNodeType()==Node.CDATA_SECTION_NODE)){
				XmlNode newChild=new XmlNode();
				node.getChild().add(newChild);
				newChild.setQname("![CDATA[");
				String context="<root>"+node1.getTextContent()+"</root>";
				XmlNode node1Child=XmlUtil.parseNode(context);
				newChild.setChild(node1Child.getChild());
				//getChildsNode(element, newChild);
			}else if((node1.getNodeType()==Node.ELEMENT_NODE)){
				// 转换为Element对象
				Element element=  (Element) nodeList.item(i);
				// 创建xml节点
				XmlNode newChild=new XmlNode();
			//	System.out.println(element.getNodeName()+"       Type:"+element.getNodeType() Node.e);
				node.getChild().add(newChild);
				newChild.setQname(element.getNodeName());
			//	newChild.setValue(element.toString());
				NamedNodeMap nameNodeMap=element.getAttributes();
				int attLength= nameNodeMap.getLength();
				if(attLength>0){
					Map<String,String> map=new HashMap<String, String>();
					newChild.setAttribute(map);
					for (int j = 0; j < attLength; j++) {
						String key= nameNodeMap.item(j).getNodeName();
						String value=nameNodeMap.item(j).getNodeValue();
						map.put(key, value);
					}
				}
					// 不是最后子节点,迭代当前节点
					getChildsNode(element, newChild);
			}else if(node1.getNodeType()==Node.TEXT_NODE){
				node.setValue(node1.getNodeValue());
			}
			
		}
	}
	/**
	 * xml的java对象转换为java字符串
	 * @param 某个父节点或根节点。
	 * */
	public static String parseXml (XmlNode root) throws ParserConfigurationException{
		String [] rootNodeNames=getNodeXmlStr(root);
		String xml=forEachRoot(root);
		xml=rootNodeNames[0]+xml+rootNodeNames[1];
		return xml;
	}
	String nodeXmlString="";
	// 递归节点。
	private static String forEachRoot(XmlNode root){
		// 获取父节点的子节点
		List<XmlNode> childs= root.getChild();
		// 当前层级的标签对
		StringBuilder getChildInfo=null;
		if(childs.size()>0){
			getChildInfo=new StringBuilder();
			// 当前节点标签数组
			String []nameInfo=null;
			for (int i = 0; i < childs.size(); i++) {
				// 当前节点
				XmlNode xmlNode=childs.get(i);
				// 获取当前节点标签对
				nameInfo=getNodeXmlStr(xmlNode);
				// 子层级标签对
				String returnInfo=forEachRoot(xmlNode);
				// 当前节点标签对包裹子节点层级标签对
				//String oneNodeInfo=nameInfo[0]+returnInfo+nameInfo[1];
				// 当前层级标签对添加当前节点标签对
				getChildInfo.append(nameInfo[0]);
				getChildInfo.append(returnInfo);
				getChildInfo.append(nameInfo[1]);
			}
			
		}
		if(getChildInfo!=null){
			return getChildInfo.toString();
		}else{
			return "";
		}
		//  返回当前层级标签对
	}
	// 获取标签对
	private static String[] getNodeXmlStr(XmlNode node){
		Map<String,String> map= node.getAttribute();
		String attbute="";
		// 迭代属性
		if(map!=null&&map.size()>0){
			for (String key:map.keySet()) {
				attbute+=" "+key+"=\""+map.get(key)+"\"";
			}
		}
		// 前标签
		String firstName="";
		// 后标签
		String lastName="";
		// 值
		String value=node.getValue()==null?"":node.getValue();
		String qname=node.getQname();
		if(qname.equals("![CDATA[")){
			firstName="<![CDATA[";
			lastName="]]>";
		}else{
			firstName=PREFIX+qname+attbute+SUFFIX+value;
			lastName=PREFIX+"/"+qname+SUFFIX;
		}
		
		return new String[]{firstName,lastName};
	}
	/*
	public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
		String xml = ""
				+"<root key='adf' name='ere'>"
				+"<node1>"
				+"<classType>test.Student</classType>"
				+"<propertys>"
				+"<fieldType>int</fieldType>"
				+"<key>age</key>"
				+"<value>8</value>"
				+"</propertys>"
				+"<propertys>"
				+"<fieldType>int</fieldType>"
				+"<key>model</key>"
				+"<value>18</value>"
				+"</propertys>"
				+"<propertys>"
				+"<fieldType>java.lang.String</fieldType>"
				+"<key>Name</key>"
				+"<value>asdfa</value>"
				+"</propertys>"
				+"</node1>"
				+"<node2>"
				+"<classType>test.Student</classType>"
				+"<propertys>"
				+"<fieldType>int</fieldType>"
				+"<key>age</key>"
				+"<value>7</value>"
				+"</propertys>"
				+"<propertys>"
				+"<fieldType>int</fieldType>"
				+"<key>model</key>"
				+"<value>19</value>"
				+"</propertys>"
				+"<propertys>"
				+"<fieldType>java.lang.String</fieldType>"
				+"<key>Name</key>"
				+"<value>sdfaa</value>"
				+"</propertys>"
				+"</node2>"
				+"</root>";
		//XmlNode root= new XmlUtil().parseNode(xml);
		XmlNode root= new XmlUtil().parseNodeByFilePath("D:\\pom.xml");
		String xmlStr=new XmlUtil().toJson(root);
		System.out.println(xmlStr);
	}
	*/
	public static String toJson(XmlNode xmlNode){
		String childString=XmlUtil.xmlToJsonString(xmlNode);
		String returnJsonString="{\""+xmlNode.getQname()+"\":"+childString+"}";
		returnJsonString=returnJsonString.replace("\"\"[", "[").replace("\"\"{", "{");
		return returnJsonString;
	}
	private static String xmlToJsonString(XmlNode xmlNode){
		// 获取父节点的子节点
		List<XmlNode> childs= xmlNode.getChild();
		// 当前层级的标签对
		StringBuilder getChildInfo=null;
		int size=childs.size();
		if(size>0){
			getChildInfo=new StringBuilder();
			// 当前节点标签数组
			String []nameInfo=null;
		
			for (int i = 0; i < size; i++) {
				// 当前节点
				XmlNode newXmlNode=childs.get(i);
				// 获取当前节点标签对
				nameInfo=getNodeJsonStr(newXmlNode);
				// 子层级标签对
				String returnInfo=xmlToJsonString(newXmlNode);
				// 当前节点标签对包裹子节点层级标签对
				//String oneNodeInfo=nameInfo[0]+returnInfo+nameInfo[1];
				// 当前层级标签对添加当前节点标签对
				getChildInfo.append(nameInfo[0]);
				getChildInfo.append(returnInfo);
				getChildInfo.append(nameInfo[1]);
				if(size>1&&i<size-1){
					getChildInfo.append(",");
				}
			}
			if(size>1){
				getChildInfo.insert(0, "[");
				getChildInfo.insert(getChildInfo.length(), "]");
			}
		}
		if(getChildInfo!=null){
			return getChildInfo.toString();
		}else{
			return "";
		}
	}
	private static String[] getNodeJsonStr(XmlNode xmlNode){
		String first="{\""+xmlNode.getQname()+"\":";
		String last="}";
		String value="\"\"";
		if(xmlNode.getValue()!=null&&!xmlNode.getValue().contains("\n")&&
				!xmlNode.getValue().contains("\t")){
			value="\""+xmlNode.getValue()+"\"";
		}
		first=first+value;
		return new String[]{first,last};
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值