server.xml
<?xml version="1.0" encoding="utf-8"?> <server> <service> <connector port ="8080"></connector> </service> </server>
package edu.aeon.xml; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; /** * [说明]:通过dom4j+xpath获取节点属性的值 * 需要导入dom4j和xpath的jar包 * @author aeon(qq:1584875179) * */ public class Dom4jXpathAttri { public static void main(String[] args) { try { SAXReader saxReader=new SAXReader(); Document document=saxReader.read("config/server.xml"); Element connectorElement = (Element) document.selectSingleNode("/server/service/connector"); //2种方式任选一种即可 Attribute attribute = connectorElement.attribute("port"); String attributeValue1=attribute.getStringValue(); String attributeValue2 = connectorElement.attributeValue("port"); System.out.println(attributeValue1+" "+attributeValue2); } catch (DocumentException e) { e.printStackTrace(); } } }
结果截图: