在xml元素中获取属性值

我有一个像这样的xml字符串,我想在每个元素的循环中获取“name”的属性值。 我怎么做? 我正在使用javax.xml.parsers库。

  Calendar Year 200 350   400 $320.00 670  8000 60 10 12        $250.00 false false  Immediate Not Applicable   

这就是我到现在为止所要做的

 DocumentBuilderFactory dbc = DocumentBuilderFactory.newInstance(); DocumentBuilder dbuilder; try { dbuilder = dbc.newDocumentBuilder(); Document doc = dbuilder.parse(new InputSource(new StringReader(plan.getProvisions()))); NodeList nl = doc.getElementsByTagName("Item"); for(int i = 0 ; i < nl.getLength(); i++){ if(i == row){ Element e = (Element)nl.item(i); description = e.getAttribute("name"); } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } 

怎么样:

 import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; public class Demo { public static void main(String[] args) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(new File("input.xml")); NodeList nodeList = document.getElementsByTagName("Item"); for(int x=0,size= nodeList.getLength(); x 

我想我明白了。 我必须明确地使用org.w3c.dom.Element 。 我也有一个不同的元素字段。

下面是在vtd-xml中执行此操作的代码。 它基本上使用XPath“/ xml / item / @ name”查询XML。

 import com.ximpleware.*; public class getAttrs{ public static void main(String[] s) throws VTDException{ VTDGen vg = new VTDGen(); if (!vg.parseFile("input.xml",false)) // turn off namespace return; VTDNav vn = vg.getNav(); AutoPilot ap = new AutoPilot(vn); ap.selectXPath("/xml/item/@name"); int i=0; while( (i=ap.evalXPath())!=-1){ System.out.println(" item name is ===>"+vn.toString(i+1)); } } }