如何XML 字符串获取属性值?
下面的示例 从XML 字符串创建一个 DOM 对象。
然后使用 XPath.selectNodes() 方法应用 XPATH 表达式。
package com.onitroad.xml; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.xpath.XPath; public class XmlAttributesUsingXPathExample { @SuppressWarnings("unchecked") public static void main(String[] args) throws JDOMException, IOException { Document doc = new SAXBuilder(false).build(new StringReader(new String( <users> " + <user id='123'>" + <firstname>Jack</firstname>" + </user>" + <user id='456'>" + <firstname>Robin</firstname>" + </user> " + <user id='789'>" + <firstname>Tom</firstname>" + </user>" + </users>"))); // 构建 xpath 表达式 XPath xpathExpression = XPath.newInstance("//*[@id]"); // 应用xpath并获取所有匹配的节点 ArrayList<Element> userIds = (ArrayList<Element>) xpathExpression.selectNodes(doc); // 遍历所有节点 for (int i = 0; i < userIds.size(); i++) { System.out.println((userIds.get(i)).getAttributeValue("id").trim()); } } }
日期:2020-09-17 00:10:15 来源:oir作者:oir