使用jdom操作xml文件 去除子节点带有命名空间

package com.soft.common;

import java.util.HashMap;
import java.util.Map;

import org.jdom2.Namespace;

/**
 * 节点操作属性封装
 * @author xingxf
 *
 */
public class Nodes {
	
	//文件路径
	private String path;
	
	//节点名称
	private String  NodeName;	
	
	//xml命名空间
	private Namespace nameSpace;
	
	//节点文本值
	private String content;		
	
	//节点属性名  key 节点属性值  value
	private Map<String, String> attribute=new HashMap<String, String>();	
	
	
	public String getPath() {
		return path;
	}
	
	public void setPath(String path) {
		this.path = path;
	}
	
	public Nodes() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Nodes(String path, String nodeName, Namespace nameSpace,
			String content, Map<String, String> attribute) {
		super();
		this.path = path;
		NodeName = nodeName;
		this.nameSpace = nameSpace;
		this.content = content;
		this.attribute = attribute;
	}
	
	public Nodes(String nodeName, String content, Map<String, String> attribute) {
		super();
		NodeName = nodeName;
		this.content = content;
		this.attribute = attribute;
	}


	public String getNodeName() {
		return NodeName;
	}
	public void setNodeName(String nodeName) {
		NodeName = nodeName;
	}
	public Namespace getNameSpace() {
		return nameSpace;
	}
	public void setNameSpace(Namespace nameSpace) {
		this.nameSpace = nameSpace;
	}


	public String getContent() {
		return content;
	}


	public void setContent(String content) {
		this.content = content;
	}


	public Map<String, String> getAttribute() {
		return attribute;
	}


	public void setAttribute(Map<String, String> attribute) {
		this.attribute = attribute;
	}

	public Map<String, String> setmap(String key,String value){
		Map<String, String> map=new HashMap<String, String>();
		map.put(key, value);
		return map;
	}

	
}

  

 

 

package com.test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

import com.soft.common.Nodes;



public class XmlOperationUtils {
	
	public static void main(String[] args) {
		try {
			XmlOperationUtils dj = new XmlOperationUtils();
	
			String file = "D:/Tomcat/webapps/oagovern/WEB-INF/flowtemplate/dd.jpdl.xml";// 设置文件路径和名称;
			Nodes nodes=new Nodes();
			nodes.setPath(file);
			nodes.setNodeName("persons");
			nodes.setNameSpace(Namespace.getNamespace("http://jbpm.org/4.4/jpdl"));
			Map<String, String> attr=new HashMap<String, String>();
			attr.put("name", "test1");
			attr.put("type", "String");
			attr.put("key", "test");
			attr.put("value", "value");
			nodes.setAttribute(attr);
			nodes.setContent("小明学习Java");
			
			//初始化xml
			dj.initXmlNode(nodes);
			
			//获取根节点
			Document document = dj.getRootElement(nodes.getPath());
			Element root=dj.getRootNode(document);
			
			//添加子级节点
			Nodes childNode=new Nodes("person", "test", nodes.setmap("name", "hello"));
			Element child =dj.createChildElement(root,childNode);	
			
			//添加子级的子级
			Nodes childNodes=new Nodes("student", "小明学习Java", nodes.setmap("type", "int"));
			dj.createChildElement(child,childNodes);
			
			
			// 生成xml
			dj.StoreXmlToFile(document, nodes.getPath());
			
			//解析xml
			dj.parserXml(file);
			
			
			
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	

	/**
	 *
	 * @param filepath 文件路径  
	 */
	public void createXml(String filepath) { 
		Document document = new Document();
		Namespace ns= Namespace.getNamespace("http://jbpm.org/4.4/jpdl");
		Element root = new Element("persons",ns).setAttribute("name", "persons");
        document.setRootElement(root);
        createChildElements(root);
        StoreXmlToFile(document, filepath);
    }  
	
	
	
	
	/**
	 * 初始化xml根节点和文件
	 * @param nodes
	 */
	public  boolean initXmlNode(Nodes nodes){
		boolean flag=false;
		if (nodes!=null) {
			
			Document document=new Document();
			
			Element root=new Element(nodes.getNodeName(),nodes.getNameSpace());
			Map<String, String> map=nodes.getAttribute();
				for (String key:map.keySet()) {
					System.out.println("key:"+key+" and value:"+map.get(key));
					root.setAttribute(key,map.get(key));
				}
			
			document.setRootElement(root);
			
			StoreXmlToFile(document, nodes.getPath());
			flag=true;
		}
		
		return flag;
	}
	
	/**
	 * 获取根节点
	 * @param document 根据路径获得的文档
	 * @return 根节点
	 */
	public Element getRootNode(Document document){
		return document.getRootElement();
	}
	
	/**
	 *  创建xml子节点  
	 * @param parent 父节点
	 * @param nodes	节点实例对象
	 */
	private Element createChildElement(Element parent ,Nodes nodes) {
		Element child=new Element(nodes.getNodeName());
		Map<String, String> map=nodes.getAttribute();
		for(String key:map.keySet()){
			child.setAttribute(key,map.get(key));
		}
		setChildElementNS(child,parent);
		child.setText(nodes.getContent());
		parent.addContent(child);
		return child;

	}
	
	/**
	 * 设置子级元素的命名空间  可以实现去除子节点命名空间
	 * @param child  ChildrenElement
	 * @param root	 RootElement
	 */
	private void setChildElementNS(Element child, Element root) {
		child.setNamespace(root.getNamespace());
	}
	
	
	/**
	 * 生成xml文件
	 * @param document xml文档
	 * @param fliePath 文件路径
	 */
	private void StoreXmlToFile(Document document, String fliePath) {
		XMLOutputter XMLOut = new XMLOutputter();
		try {
			Format f = Format.getPrettyFormat();
			f.setEncoding("UTF-8");// default=UTF-8
			XMLOut.setFormat(f);
			XMLOut.output(document, new FileOutputStream(fliePath));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	
	/**
	 * 添加xml文件节点内容
	 * @param root 根节点
	 */
	private void createChildElements(Element root) {
		
		//在root节点下创建子节点
		Element person = new Element("person"); 
		person.setNamespace(root.getNamespace());
        root.addContent(person); 
        
        Element name = new Element("name");  
        name.setText("java小强");
        name.setNamespace(root.getNamespace());
        person.addContent(name);
        
        Element sex = new Element("sex");  
        sex.setText("man");
        sex.setNamespace(root.getNamespace());
        person.addContent(sex); 
       
       
        Element start=new Element("start").setAttribute("name", "satrt1");
        start.setAttribute("class", "start");
        start.setNamespace(root.getNamespace());
        root.addContent(start);
        
        Element trations=new Element("trations");
        setChildElementNS(trations, root);
        start.addContent(trations);
        
        Element heand=new Element("heand");
        heand.setText("Java操作");
        setChildElementNS(heand, root);
        trations.addContent(heand);
       
	}
	
	/**
	 * 根据路径获取xml文档
	 * @param file 文件路径
	 */
	public Document getRootElement(String file) throws JDOMException, IOException{
			SAXBuilder builder=new SAXBuilder();
			return builder.build(file);
	}
	
	
	
	 /**   
     * 解析XML   
     * @param filePath 文件路径   
     */   
    public void parserXml(String file) {  
        try {  
        	Document document=getRootElement(file);
            Element root = document.getRootElement();
            List persons = root.getChildren("person");  
            for (int i = 0; i < persons.size(); i++) {  
                Element person = (Element) persons.get(i);  
                List pros = person.getChildren();  
                for (int j = 0; j < pros.size(); j++) {  
                    Element element = (Element) pros.get(j);  
                    System.out.println(element.getName() + ":" + element.getValue());  
                }  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
}  

  jdom-2.0.6.jar

解决思路:

  理论:当命名空间被定义在元素的开始标签中时,所有带有相同前缀的子元素都会与同一个命名空间相关联。

  方法:为该xml的子节点添加与父节点相同的命名空间方法 可以去除子节点含有命名空间

 

下载链接

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值