我如何通过XPath读取XML

时间:2014-04-11 20:46:32

标签: java xml xpath

我有方法从My XML文件中读取XML,我使用xpath从XML文件中获取元素,但总是让我的对象为null。 我想得到所有的值元素,但是给我null。

我的方法:

public ArrayList<Object> GetAnyEntity(String PathXPath) throws JAXBException {
        ArrayList<Object> list = new ArrayList<Object>();
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = domFactory.newDocumentBuilder();
            Document dDoc = builder.parse("Projects//asdad//ProjectDataBase.xml");
            XPath xPath = XPathFactory.newInstance().newXPath();
            NodeList nl = (NodeList)xPath.evaluate("//Project/Layer[@idLayer=2]", dDoc, XPathConstants.NODESET);
            for (int i = 0; i < nl.getLength(); i++) {
                list.add(nl.item(i));
            }
        } catch (Exception e) { 
            e.printStackTrace();
        }
        return list;
    } 

XML文件:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Project xmlns="http://www.example.org/ProjectDataBase" name="name1" >
    <Layer idLayer="2">
        <LayerName>a</LayerName>
        <Order>2</Order>
        <Visible>false</Visible>
    </Layer>
</Project>

1 个答案:

答案 0 :(得分:0)

你正在崛起&#39;&#39;围绕2:

//Project/Layer[@idLayer='2']