2015-10-07 4 views
0

У меня есть файл XML, как:Java-код для разбора части XML-файл

<db> 
<employees name="aaa"> 
    <employee id="111"> 
    <firstName>Rakesh</firstName> 
    <lastName>Mishra</lastName> 
    <location>Bangalore</location> 
    </employee> 
    <employee id="112"> 
    <firstName>John</firstName> 
    <lastName>Davis</lastName> 
    <location>Chennai</location> 
    </employee> 
    <employee id="113"> 
    <firstName>Rajesh</firstName> 
    <lastName>Sharma</lastName> 
    <location>Pune</location> 
    </employee> 
</employees> 

<employees name="bbb"> 
    <employee id="222"> 
    <firstName>a</firstName> 
    <lastName>a</lastName> 
    <location>a</location> 
    </employee> 
    <employee id="223"> 
    <firstName>s</firstName> 
    <lastName>s</lastName> 
    <location>s</location> 
    </employee> 
    <employee id="224"> 
    <firstName>d</firstName> 
    <lastName>d</lastName> 
    <location>d</location> 
    </employee> 
</employees> 
</db> 

Есть ли способ, где я могу разобрать только первую часть сотрудников т.е. данных внутри <employees name="aaa"> и </employees>

Моего Явы код выглядит следующим образом:

public static void main(String args[]) { 
try { 

File stocks = new File("C:\\employee.xml"); 
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 

DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 

Document doc = dBuilder.parse(stocks); 

doc.getDocumentElement().normalize(); 
deList nodes = doc.getElementsByTagName("employee"); 
for (int i = 0; i < nodes.getLength(); i++) { 

Node node = nodes.item(i); 

if (node.getNodeType() == Node.ELEMENT_NODE) { 
Element element = (Element) node; 
System.out.println("\nStock firstName: " + getValue("firstName", element)); 
} 

} 

} catch (Exception ex) { 

ex.printStackTrace(); 

} 

} 

private static String getValue(String tag, Element element) { 

NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes(); 

Node node = (Node) nodes.item(0); 

return node.getNodeValue(); 

} 

в этом коде я не могу пометить, как

deList nodes = doc.getElementsByTagName("employee name="aaa""); 

Я даже создал строку этого имени enitre и передал, но все равно никаких решений. Может ли кто-нибудь помочь мне в этом.

+0

Вы можете использовать SAX парсер или XPath для запроса DOM, то вроде '/ дб/сотрудников [@ имя =«ааа»]/employee' должен вернуть все' employee' узлы, которые являются дочерними '/ db/employees' с атрибутом' name', равным 'aaa' – MadProgrammer

+0

ok я буду искать его спасибо – BJK

ответ

0
import javax.xml.xpath.XPath; 
import javax.xml.xpath.XPathFactory; 
//your code 
XPath xPath = XPathFactory.newInstance().newXPath(); 
String expression = "db/employees[@name='aaa']/employee"; 
NodeList nodeList =(NodeList)xPath.compile(expression).evaluate(xmlDocument,XPathConstants.NODESET); 
for (int i = 0; i < nodeList.getLength(); i++) { 
System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
} 
0

Вы можете использовать выражения XPath.

public static void main(String[] args) { 

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder builder = null; 

    try { 

     File stocks = new File("D:\\EmpDetails.xml"); 
     builder = builderFactory.newDocumentBuilder(); 
     Document document = builder.parse(stocks); 
     XPath xPath = XPathFactory.newInstance().newXPath(); 
     String expression = "//employees[@name='aaa']/employee/firstName"; 
     NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET); 
     //System.out.println("length is " + nodeList.getLength()); 
     for (int i = 0; i < nodeList.getLength(); i++) { 
      System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
     } 

    } catch (SAXException ex) { 
     Logger.getLogger(ReadXML.class.getName()).log(Level.SEVERE, null, ex); 
    } catch (IOException ex) { 
     Logger.getLogger(ReadXML.class.getName()).log(Level.SEVERE, null, ex); 
    } catch (XPathExpressionException ex) { 
     Logger.getLogger(ReadXML.class.getName()).log(Level.SEVERE, null, ex); 
    } catch (ParserConfigurationException e) { 
     e.printStackTrace(); 
    } 
} 
Смежные вопросы