1,将xml字符串解析为xml
Document doc = DocumentHelper.parseText(xml); // 将字符串转为XML
2,遍历xml通过指定一个参数获取其他参数的值
xml文件:
方法:
import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.SAXReader; //---------------- public String getXmlvalueByKey(String xmlString, String key) { String value = null; Element placard = null; Document document = null; SAXReader reader = new SAXReader(); try { // document = reader.read(new File("E:/temp/test.xml")); //解析xml文件 document = DocumentHelper.parseText(xmlString); // 解析xml字符串 placard = document.getRootElement(); Element item = (Element) placard.selectSingleNode("/nodes/node[@key='" + key + "']"); if (item != null) { value = item.attributeValue("value"); } } catch (DocumentException e) { e.printStackTrace(); } return value; }
测试方法:
@Test public void test1() throws Exception{ String xmlString =""; //查找xml文件key的值 String value=new ExcelOperationUtil().getXmlvalueByKey(xmlString,"key1"); System.out.println(value);//输出结果value1 }