对xml文档操作的常用方法

本文介绍了一个用于操作XML文档的实用类,提供了加载、保存、查询节点等多种功能,并详细展示了如何使用这些方法来管理和修改XML文件。
java 代码
  1.   
  2. import java.io.*;   
  3. import java.util.*;   
  4.   
  5. import javax.xml.XMLConstants;   
  6. import javax.xml.parsers.DocumentBuilder;   
  7. import javax.xml.parsers.DocumentBuilderFactory;   
  8. import javax.xml.transform.Source;   
  9. import javax.xml.transform.dom.DOMSource;   
  10. import javax.xml.transform.stream.StreamSource;   
  11. import javax.xml.validation.Schema;   
  12. import javax.xml.validation.SchemaFactory;   
  13. import javax.xml.validation.Validator;   
  14.   
  15. import org.dom4j.*;   
  16. import org.dom4j.io.*;   
  17. import org.xml.sax.SAXException;   
  18.   
  19. /**  
  20.  * name:XMLUtil.java  
  21.  *   
  22.  * desc: 本类是xml文档操作实用类,提供对xml文档操作的常用方法。  
  23.  *  
  24.  */  
  25.   
  26. public class XMLUtil   
  27. {   
  28.     private Document doc;   
  29.        
  30.     /**  
  31.      * 构造函数  
  32.      *  
  33.      */  
  34.     public XMLUtil()   
  35.     {   
  36.            
  37.     }   
  38.        
  39.     /**  
  40.      * 方法完成xml文件的加载,在调用本类的其他方法前需要调用loadFromFile()或者loadFromString()  
  41.      * @param file xml文件对象  
  42.      * @throws Exception  
  43.      */  
  44.     public void loadFromFile(File file)throws Exception   
  45.     {   
  46.         //参数无效   
  47.         if (file == null || !file.exists() || file.isDirectory())   
  48.         {   
  49.             throw new IllegalArgumentException("xml file is not valid!");   
  50.         }   
  51.         SAXReader saxReader = new SAXReader();   
  52.         doc = saxReader.read(file);   
  53.     }   
  54.        
  55.     /**  
  56.      * 方法完成xml格式字符串的加载,转换成xml文档形式,注意参数必须符合xml格式,  
  57.      * 否则后续操作会出错  
  58.      * @param contents xml格式的字符串  
  59.      * @throws Exception  
  60.      */  
  61.     public void loadFromString(String contents)throws Exception   
  62.     {   
  63.         //参数无效   
  64.         if (contents == null || contents.trim().length() == 0)   
  65.         {   
  66.             throw new IllegalArgumentException("argument is not valid!");   
  67.         }   
  68.         doc = DocumentHelper.parseText(contents);   
  69.     }   
  70.        
  71.     /**  
  72.      * 方法执行xml文档的保存  
  73.      * @param filePath xml文件保存路径  
  74.      * @param encoding xml文件编码格式(gb2312|utf-8|gbk等)  
  75.      * @throws IOException  
  76.      * @throws Exception  
  77.      */  
  78.     public void dump(String filePath, String encoding)throws IOException, Exception   
  79.     {   
  80.         //参数无效   
  81.         if (filePath == null || filePath.trim().length() == 0)   
  82.         {   
  83.             throw new IllegalArgumentException("store path is not valid!");   
  84.         }   
  85.         encoding = (encoding == null || encoding.trim().length() == 0) ? "gb2312" : encoding;   
  86.         OutputFormat format = OutputFormat.createPrettyPrint();   
  87.         format.setEncoding(encoding);   
  88.         format.setIndent("  ");   
  89.         FileWriter fileWriter = new FileWriter(filePath);   
  90.         XMLWriter xmlWriter = new XMLWriter(fileWriter, format);   
  91.         try  
  92.         {   
  93.             xmlWriter.write(doc);   
  94.         }   
  95.         catch(Exception e)   
  96.         {   
  97.             throw e;   
  98.         }   
  99.         finally  
  100.         {   
  101.             xmlWriter.close();   
  102.             xmlWriter = null;   
  103.             fileWriter.close();   
  104.             fileWriter = null;   
  105.         }   
  106.            
  107.     }   
  108.        
  109.        
  110.     /**  
  111.      * 方法获取单个指定节点名的节点  
  112.      * @param name 节点名,支持Xpath  
  113.      * @param index 节点出现的索引位置  
  114.      * @return 找到返回Element,没找到返回null.  
  115.      * @throws Exception  
  116.      */  
  117.     public Element getElement(String name, int index)throws Exception   
  118.     {   
  119.         //节点名无效   
  120.         if (!isValidate(name))   
  121.         {   
  122.             throw new IllegalArgumentException("the element's name is not valid!");   
  123.         }   
  124.            
  125.         //索引位置无效   
  126.         if (index < 0)   
  127.         {   
  128.             throw new IllegalArgumentException("the element's index is not valid!");   
  129.         }   
  130.         List elementsList = doc.selectNodes("//" + name);   
  131.            
  132.         //指定的节点名存在并且索引有效   
  133.         if (elementsList != null && elementsList.size() > index)   
  134.         {   
  135.             return (Element)elementsList.get(index);   
  136.         }   
  137.         return null;   
  138.     }   
  139.        
  140.     /**  
  141.      * 方法获取指定节点名的节点list  
  142.      * @param name 节点名  
  143.      * @return 节点list  
  144.      * @throws Exception  
  145.      */  
  146.     public ArrayList getElements(String name)throws Exception   
  147.     {   
  148.         //节点名无效   
  149.         if (!isValidate(name))   
  150.         {   
  151.             throw new IllegalArgumentException("element name is not valid!");   
  152.         }   
  153.         List list = doc.selectNodes("//" + name);   
  154.         ArrayList <Element>arrayList = new ArrayList<Element>();   
  155.         //存在节点时,循环获取每一个节点   
  156.         if (list != null)   
  157.         {   
  158.             int length = list.size();   
  159.             for (int i = 0; i < length; i++)   
  160.             {   
  161.                 Node node = (Node)list.get(i);   
  162.                    
  163.                 //节点是element实例时,添加到arrayList   
  164.                 if (node instanceof Element)   
  165.                 {   
  166.                     arrayList.add((Element)node);   
  167.                 }   
  168.             }   
  169.         }   
  170.         return arrayList;   
  171.     }   
  172.        
  173.     /**  
  174.      * 方法获取一个节点的子节点信息  
  175.      * @param element 节点  
  176.      * @param subElementName 子节点名称  
  177.      * @return 子节点list,每个list元素是一个Element  
  178.      * @throws Exception  
  179.      */  
  180.     public ArrayList getSubElements(Element element, String subElementName)throws Exception   
  181.     {   
  182.         //参数无效   
  183.         if (element == null)   
  184.         {   
  185.             throw new IllegalArgumentException("element is null!");   
  186.         }   
  187.            
  188.         //参数无效   
  189.         if (!isValidate(subElementName))   
  190.         {   
  191.             throw new IllegalArgumentException("sub element name is invalid!");   
  192.         }   
  193.         return (ArrayList)element.elements(subElementName);   
  194.     }   
  195.        
  196.     /**  
  197.      * 方法获取单个节点值  
  198.      * @param name 节点名  
  199.      * @return 节点值  
  200.      * @throws Exception  
  201.      */  
  202.     public String getElementValue(String name)throws Exception   
  203.     {   
  204.         //invalid argument   
  205.         if (!isValidate(name))   
  206.         {   
  207.             throw new IllegalArgumentException("argument is not valid!");   
  208.         }   
  209.         Node node = doc.selectSingleNode("//" + name);   
  210.            
  211.         //return the value   
  212.         if (node instanceof Element)   
  213.         {   
  214.             return node.getText().trim();   
  215.         }   
  216.         return "";   
  217.     }   
  218.        
  219.        
  220.     /**  
  221.      * 方法获取指定节点名的节点值的properties,重复的节点值将过滤掉  
  222.      * @param name 节点名  
  223.      * @return 节点值properties  
  224.      * @throws Exception  
  225.      */  
  226.     public Properties getElementValues(String name)throws Exception   
  227.     {   
  228.         if (!isValidate(name))   
  229.         {   
  230.             throw new IllegalArgumentException("elememt name is not valid!");   
  231.         }   
  232.         List elementList = doc.selectNodes("//" + name);   
  233.         Properties properties = new Properties();   
  234.         //节点存在   
  235.         if (elementList != null && elementList.size() > 0)   
  236.         {   
  237.                
  238.             int length = elementList.size();   
  239.             for (int i = 0; i < length; i++)   
  240.             {   
  241.                 String elementValue = ((Element)elementList.get(i)).getTextTrim();    
  242.                 properties.put(elementValue, elementValue);   
  243.             }   
  244.             return properties;   
  245.         }   
  246.         return properties;   
  247.     }   
  248.        
  249.     /**  
  250.      * 方法返回指定节点的属性信息  
  251.      * @param element 节点  
  252.      * @return 以name,value形式存在的属性  
  253.      * @throws Exception  
  254.      */  
  255.     public Properties getElementProperties(Element element)throws Exception   
  256.     {   
  257.         //参数无效   
  258.         if (element == null)   
  259.         {   
  260.             throw new IllegalArgumentException("element is null!");   
  261.         }   
  262.         List attributes = element.attributes();   
  263.         Properties properties = new Properties();   
  264.         for (int i = 0; i < attributes.size(); i++)   
  265.         {   
  266.             Attribute attr = (Attribute)attributes.get(i);   
  267.             properties.put(attr.getName(), attr.getValue());   
  268.         }   
  269.         return properties;   
  270.     }   
  271.        
  272.     /**  
  273.      * 方法返回节点的属性信息  
  274.      * @param elementName 节点名称  
  275.      * @return 以name,value形式存在的属性  
  276.      * @throws Exception  
  277.      */  
  278.     public Properties getElementProperties(String elementName)throws Exception   
  279.     {   
  280.         //参数无效   
  281.         if (!isValidate(elementName))   
  282.         {   
  283.             throw new IllegalArgumentException("element name is invalid!");   
  284.         }   
  285.         return this.getElementProperties(this.getElement(elementName, 0));   
  286.     }   
  287.        
  288.     /**  
  289.      * 方法执行节点名的更改  
  290.      * @param oldName 原始节点名  
  291.      * @param newName 更改后节点名  
  292.      * @param index 要更改的节点索引(索引指在xml文件中节点出现的位置)  
  293.      * @throws Exception  
  294.      */  
  295.     public void renameElement(String oldName, String newName, int index)throws Exception   
  296.     {   
  297.         //原始节点名无效   
  298.         if (!isValidate(oldName))   
  299.         {   
  300.             throw new IllegalArgumentException("original element name is not valid!");   
  301.         }   
  302.            
  303.         //新的节点名无效   
  304.         if (!isValidate(newName))   
  305.         {   
  306.             throw new IllegalArgumentException("new element name is not valid!");   
  307.         }   
  308.         Element element = getElement(oldName, index);   
  309.         //指定的节点不存在   
  310.         if (element == null)   
  311.         {   
  312.             throw new Exception("can not find element, which name is : " + oldName   
  313.                                   + " index is : " + index);   
  314.                
  315.         }   
  316.         element.setName(newName);   
  317.     }   
  318.        
  319.     /**  
  320.      * 方法执行节点名的更改  
  321.      * @param oldName 原始节点名  
  322.      * @param newName 更改后节点名  
  323.      * @throws Exception  
  324.      */  
  325.     public void renameElements(String oldName, String newName)throws Exception   
  326.     {   
  327.         //原始节点名无效   
  328.         if (!isValidate(oldName))   
  329.         {   
  330.             throw new IllegalArgumentException("original element name is not valid!");   
  331.         }   
  332.            
  333.         //新的节点名无效   
  334.         if (!isValidate(newName))   
  335.         {   
  336.             throw new IllegalArgumentException("new element name is not valid!");   
  337.         }   
  338.         ArrayList list = getElements(oldName);   
  339.            
  340.         //不存在该节点名   
  341.         if (list == null)   
  342.         {   
  343.             throw new Exception("can not find any element, which name is : " + oldName);   
  344.         }   
  345.            
  346.         //循环更改节点名   
  347.         int length = list.size();   
  348.         for (int i = 0; i < length; i++)   
  349.         {   
  350.             ((Element)list.get(i)).setName(newName);   
  351.         }   
  352.     }   
  353.        
  354.     /**  
  355.      * 方法执行子节点的添加,要添加的子节点必须存在父节点,添加子节点的属性可以为空。  
  356.      * @param parent 父节点名  
  357.      * @param index 父节点的索引(存在同名父节点时,在第index个父节点处添加子节点)  
  358.      * @param current 子节点名  
  359.      * @param currentValue 子节点值  
  360.      * @param attributes 子节点属性  
  361.      * @throws Exception  
  362.      */  
  363.     public void addSubElement(String parent, int index, String current, String currentValue,    
  364.                                 Properties attributes)throws Exception   
  365.     {   
  366.         //父节点无效   
  367.         if (!isValidate(parent))   
  368.         {   
  369.             throw new IllegalArgumentException("parent element is not valid!");   
  370.         }   
  371.            
  372.         //当前节点无效   
  373.         if (!isValidate(current))   
  374.         {   
  375.             throw new IllegalArgumentException("current element is not valid!");   
  376.         }   
  377.            
  378.         Element parentElement = getElement(parent, index);   
  379.            
  380.         //指定的父节点不存在   
  381.         if (parentElement == null)   
  382.         {   
  383.             throw new Exception("can not find the specified parent element, which name is :"  
  384.                                  + parent);   
  385.         }   
  386.         Element currentElement = parentElement.addElement(current);   
  387.            
  388.         //节点值有效   
  389.         if (currentValue != null && currentValue.length() > 0)   
  390.         {   
  391.             currentElement.setText(currentValue);   
  392.         }   
  393.            
  394.         //存在属性时,添加节点属性   
  395.         if (attributes != null)   
  396.         {   
  397.             Enumeration e = attributes.keys();   
  398.             while (e.hasMoreElements())   
  399.             {   
  400.                 Object attrName = e.nextElement();   
  401.                 Object attrValue = attributes.get(attrName);   
  402.                 currentElement.addAttribute(attrName.toString(), attrValue.toString());   
  403.             }   
  404.         }   
  405.     }   
  406.        
  407.     /**  
  408.      * 方法执行子节点的添加,要添加的子节点必须存在父节点,  
  409.      * @param parent 父节点名  
  410.      * @param index 父节点在xml文档中的索引  
  411.      * @param childList 子节点list,每个list元素是一个Element  
  412.      * @throws Exception  
  413.      */  
  414.     public void addSubElements(String parent, int index, ArrayList childList)   
  415.     throws Exception   
  416.     {   
  417.         Element parentElement = getElement(parent, index);   
  418.         //指定的父节点不存在   
  419.         
【语音分离】基于平均谐波结构建模的无监督单声道音乐声源分离(Matlab代码实现)内容概要:本文介绍了基于平均谐波结构建模的无监督单声道音乐声源分离方法,并提供了相应的Matlab代码实现。该方法通过对音乐信号中的谐波结构进行建模,利用音源间的频率特征差异,实现对混合音频中不同乐器或人声成分的有效分离。整个过程无需标注数据,属于无监督学习范畴,适用于单通道录音场景下的语音与音乐分离任务。文中强调了算法的可复现性,并附带完整的仿真资源链接,便于读者学习与验证。; 适合人群:具备一定信号处理基础和Matlab编程能力的高校学生、科研人员及从事音频处理、语音识别等相关领域的工程师;尤其适合希望深入理解声源分离原理并进行算法仿真实践的研究者。; 使用场景及目标:①用于音乐音频中人声与伴奏的分离,或不同乐器之间的分离;②支持无监督条件下的语音处理研究,推动盲源分离技术的发展;③作为学术论文复现、课程项目开发或科研原型验证的技术参考。; 阅读建议:建议读者结合提供的Matlab代码与网盘资料同步运行调试,重点关注谐波建模与频谱分解的实现细节,同时可扩展学习盲源分离中的其他方法如独立成分分析(ICA)或非负矩阵分解(NMF),以加深对音频信号分离机制的理解。
内容概要:本文系统介绍了新能源汽车领域智能底盘技术的发展背景、演进历程、核心技术架构及创新形态。文章指出智能底盘作为智能汽车的核心执行层,通过线控化(X-By-Wire)和域控化实现驱动、制动、转向、悬架的精准主动控制,支撑高阶智能驾驶落地。技术发展历经机械、机电混合到智能三个阶段,当前以线控转向、线控制动、域控制器等为核心,并辅以传感器、车规级芯片、功能安全等配套技术。文中还重点探讨了“智能滑板底盘”这一创新形态,强调其高度集成化、模块化优势及其在成本、灵活性、空间利用等方面的潜力。最后通过“2025智能底盘先锋计划”的实车测试案例,展示了智能底盘在真实场景中的安全与性能表现,推动技术从研发走向市场验证。; 适合人群:汽车电子工程师、智能汽车研发人员、新能源汽车领域技术人员及对智能底盘技术感兴趣的从业者;具备一定汽车工程或控制系统基础知识的专业人士。; 使用场景及目标:①深入了解智能底盘的技术演进路径与系统架构;②掌握线控技术、域控制器、滑板底盘等关键技术原理与应用场景;③为智能汽车底盘研发、系统集成与技术创新提供理论支持与实践参考。; 阅读建议:建议结合实际车型和技术标准进行延伸学习,关注政策导向与行业测试动态,注重理论与实车验证相结合,全面理解智能底盘从技术构想到商业化落地的全过程。
【顶级EI复现】计及连锁故障传播路径的电力系统 N-k 多阶段双层优化及故障场景筛选模型(Matlab代码实现)内容概要:本文介绍了名为《【顶级EI复现】计及连锁故障传播路径的电力系统 N-k 多阶段双层优化及故障场景筛选模型(Matlab代码实现)》的技术资源,重点围绕电力系统中连锁故障的传播路径展开研究,提出了一种N-k多阶段双层优化模型,并结合故障场景筛选方法,用于提升电力系统在复杂故障条件下的安全性与鲁棒性。该模型通过Matlab代码实现,具备较强的工程应用价值和学术参考意义,适用于电力系统风险评估、脆弱性分析及预防控制策略设计等场景。文中还列举了大量相关的科研技术支持方向,涵盖智能优化算法、机器学习、路径规划、信号处理、电力系统管理等多个领域,展示了广泛的仿真与复现能力。; 适合人群:具备电力系统、自动化、电气工程等相关背景,熟悉Matlab编程,有一定科研基础的研究生、高校教师及工程技术人员。; 使用场景及目标:①用于电力系统连锁故障建模与风险评估研究;②支撑高水平论文(如EI/SCI)的模型复现与算法验证;③为电网安全分析、故障传播防控提供优化决策工具;④结合YALMIP等工具进行数学规划求解,提升科研效率。; 阅读建议:建议读者结合提供的网盘资源,下载完整代码与案例进行实践操作,重点关注双层优化结构与场景筛选逻辑的设计思路,同时可参考文档中提及的其他复现案例拓展研究视野。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值