获取XML中的childNodes的属性值

时间:2015-02-01 18:36:05

标签: android xml dom

我试图在XML文件中获取第二个孩子的价值,但对我来说似乎很难,所以如果你能帮助我,我将非常感激。我需要在没有Rob的情况下获取名称BobVictorTom ..最后,String表达式应为"//main"

 <main id="Tom">
      <asd name="Rob">
      </asd>
      <qwe name="Bob">
      </qwe>
      <iop name="Victor">
      </iop>
 </main>

这就是我到目前为止所做的......

public void getXML(String direction)throws Exception{
    String[] stops = new String[22];
    InputSource inputSrc = new InputSource(getResources().openRawResource(R.raw.bus_time));
    XPath xpath = XPathFactory.newInstance().newXPath();
    String expression = "//main" ;
    NodeList nodes = (NodeList) xpath.evaluate(expression,inputSrc,XPathConstants.NODESET);


    if(nodes != null && nodes.getLength() > 0) {
        for (int i = 0; i < nodes.getLength(); ++i) {
            Node node = nodes.item(i);
            NodeList child = node.getChildNodes();

            for(int k=0; k<child.getLength();k++) {
                Node asd = child.item(k);
                NamedNodeMap attr = asd.getAttributes();
                for (int a = 0; a < attr.getLength(); a++) {
                    stops[a]  = attr.item(a).getNodeValue();
                    Toast.makeText(this, String.valueOf(stops[a]), Toast.LENGTH_LONG).show();

                }
            }

        }
    }

}

我从Toast收到的结果= null

1 个答案:

答案 0 :(得分:0)

方法node.getChildNodes()返回一些类型为等于TEXT_NODE的元素,这不是您要查找的那种,并且在尝试访问其属性时失败。为了使您的代码有效,您必须在尝试获取所需属性之前检查asd.getNodeType()== Node.ELEMENT_NODE。 因此,请将此条件添加到以下代码中:

if (asd.getNodeType() == Node.ELEMENT_NODE) {             
  NamedNodeMap attr = asd.getAttributes();
                for (int a = 0; a < attr.getLength(); a++) {
                    stops[a]  = attr.item(a).getNodeValue();
                    Toast.makeText(this, stops[a], Toast.LENGTH_LONG).show();

                }
}

但是你可以让它变得更简单,你不需要遍历属性来获取特定属性,只需将其转换为Element并通过属性名称访问它,如:

if (asd.getNodeType() == Node.ELEMENT_NODE) {             

  Toast.makeText(this, ((Element)asd).getAttribute("name"), Toast.LENGTH_LONG).show();

}

或另一种方式:

if (asd instanceof Element) {             

  Toast.makeText(this, ((Element)asd).getAttribute("name"), Toast.LENGTH_LONG).show();

}