xml文件内容:
<devices>
<device id="htc" user_agent="Mozilla">
<group id="product_info">
<capability name="model_name" value="Desire ADR6200"/>
<capability name="user_name" value="andy"/>
</group>
<group id="xhtml_ui">
<capability name="cookie" value="false"/>
</group>
</device>
</devices>
现在需要通过java来解析这个文件,不知道dom解析是否可以;
我需要获取的内容:
1.device标签上user_agent属性的值;
2.group标签中id为product_info下面capability标签name为model_name的:name和value
这个xml文件中会有很多个device节点,请高人给出java解析代码,万分感谢!!!分不多了望谅解!
------解决方案--------------------
- Java code
import org.dom4j.*;import org.dom4j.io.SAXReader;import java.util.List;public class XmlDemo { public static void main(String[] args) throws Exception { SAXReader reader = new SAXReader(); Document doc = reader.read("demo.xml"); // device[@user_agent] // 查找有user_agent属性的device节点 XPath xpathSelector = DocumentHelper.createXPath("//device[@user_agent]"); List nodes = xpathSelector.selectNodes(doc); for (Object obj : nodes) { Element n = (Element) obj; System.out.println(n.attribute("user_agent").getText()); } }}