首先先看一下我们的XML文档结构,一下的文档结构是由一对<list>标签包含,其中一组<ErrorID>包含了两个标签<ErrorCode>跟<ErrorMsg>,其中<ErrorCode>可以看成是key,
<ErrorMsg>可以看成是value。这样的话就可以通过<ErrorCode>的值来拿到<ErrorMsg>的值。
<?xml version="1.0" encoding="UTF-8"?> <list> <ErrorID id="1"> <ErrorCode>00000</ErrorCode> <ErrorMsg>成功</ErrorMsg> </ErrorID> <ErrorID id="2"> <ErrorCode>00001</ErrorCode> <ErrorMsg>处理失败</ErrorMsg> </ErrorID> <ErrorID id="3"> <ErrorCode>00002</ErrorCode> <ErrorMsg>用户原密码不正确!</ErrorMsg> </ErrorID> <ErrorID id="4"> <ErrorCode>00003</ErrorCode> <ErrorMsg>网络原因,推送失败!</ErrorMsg> </ErrorID> <ErrorID id="5"> <ErrorCode>00004</ErrorCode> <ErrorMsg>其他原因!</ErrorMsg> <pre name="code" class="html"> </ErrorID> </list>看完文档结构,以下是生成该XML文档的java类
package cn.com.sinosoft.sfjy.util; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.XMLWriter; import cn.com.sinosoft.sfjy.vo.ErrorVo; public class TestWriteXMLDemo { public static void main(String[] args) { List<ErrorVo> ErrorVoList = new ArrayList<ErrorVo>(); ErrorVoList.add(new ErrorVo("1","00000", "成功")); ErrorVoList.add(new ErrorVo("2","00001", "处理失败")); ErrorVoList.add(new ErrorVo("3","00002", "用户原密码不正确!"));; ErrorVoList.add(new ErrorVo("5","00003", "网络原因,推送失败!")); ErrorVoList.add(new ErrorVo("8","00004", "其他原因!")); Document doc = DocumentHelper.createDocument(); Element root = doc.addElement("list"); for(ErrorVo ErrorVo : ErrorVoList){ //根节点 Element idEle = root.addElement("ErrorID"); //ErrorVoID下的元素 Element codeEle = idEle.addElement("ErrorCode"); codeEle.addText(ErrorVo.getErrorCode()); Element msgEle = idEle.addElement("ErrorMsg"); msgEle.addText(ErrorVo.getErrorMsg()); //给ErrorVoID加值 idEle.addAttribute("id", ErrorVo.getErrorID()+""); } try { XMLWriter writer = new XMLWriter(); FileOutputStream fos = new FileOutputStream("TEST.xml"); writer.setOutputStream(fos); writer.write(doc); writer.close(); } catch (Exception e) { e.printStackTrace(); } } }
package cn.com.sinosoft.sfjy.util; import java.io.File; import java.util.ArrayList; import java.util.List; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class TestParserXMLDemo { public String Test(String errorcode) { try{ SAXReader reader = new SAXReader(); // String path = 注意路徑的位置 Document doc = reader.read(new File("TEST.xml")); Element root = doc.getRootElement(); List<Element> elements = root.elements(); for(Element ele : elements){ //解析 Element codeEle = ele.element("ErrorCode"); String errorCode = codeEle.getText(); Element msgEle = ele.element("ErrorMsg"); String errorMsg = msgEle.getText(); if(errorcode.equals(errorCode)){ return errorMsg; } } }catch(Exception e){ e.printStackTrace(); } return ""; } public static void main(String[] args) { TestParserXMLDemo t1 = new TestParserXMLDemo(); System.out.println(t1.Test("00000")); } }