1,将xml字符串解析为xml
Document doc = DocumentHelper.parseText(xml); // 将字符串转为XML
2,遍历xml通过指定一个参数获取其他参数的值
xml文件:
<nodes> <node key=‘key0‘ value=‘value0‘ /> <node key=‘key1‘ value=‘value1‘ /> <node key=‘key2‘ value=‘value2‘ /> <node key=‘key3‘ value=‘value3‘ /> <node key=‘key4‘ value=‘value4‘ /> </nodes>
方法:
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 ="<nodes><node key=‘key0‘ value=‘value0‘ /><node key=‘key1‘ value=‘value1‘ /><node key=‘key2‘ value=‘value2‘ /><node key=‘key3‘ value=‘value3‘ /><node key=‘key4‘ value=‘value4‘ /></nodes>"; //查找xml文件key的值 String value=new ExcelOperationUtil().getXmlvalueByKey(xmlString,"key1"); System.out.println(value);//输出结果value1 }
时间: 2024-12-27 09:29:37