这篇文章主要是来读取XML的属性。
引入jar包:dom4j-1.6.1.jar
代码如下:
import org.dom4j.Attribute;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.DocumentHelper;import org.dom4j.Element;public class Stringdd3 {public static void main(String[] args) throws Exception {String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><document type=\"mystyle\" name=\"名字\" password=\"123456\"/>"; try {Document document = DocumentHelper.parseText(xml);Element rootElement = document.getRootElement();for (int i = 0; i < rootElement.attributeCount(); i++) {Attribute name = rootElement.attribute(i);String names = name.getName();String value = rootElement.attributeValue(names);System.out.println(names+":"+value+" ");}} catch (DocumentException e) {// TODO Auto-generated catch blocke.printStackTrace();}String xmls = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><document><child type=\"mystyle\" name=\"名字\" password=\"123456\"/></document>"; try {Document document = DocumentHelper.parseText(xmls);Element rootElement = document.getRootElement();Element childElement = rootElement.element("child");for (int i = 0; i < childElement.attributeCount(); i++) {Attribute name = childElement.attribute(i);String names = name.getName();String value = childElement.attributeValue(names);System.out.println(names+":"+value+" ");}} catch (DocumentException e) {// TODO Auto-generated catch blocke.printStackTrace();}//获取某个属性节点的子节点的值File file = new File("MrchMessage.xml");SAXReader reader = new SAXReader();Document document = null;document = reader.read(file);List<Node> list = document.selectNodes("/root/LicenseNo");for (Node node : list) {String codeName = node.selectSingleNode("@name").getText().trim();if ("123".equals(codeName)) {System.out.println("Mrch "+node.selectSingleNode("Mrch").getText());}}}}
结果:
//获取某个属性节点的子节点的值
结果: