1
<?xml version="1.0" encoding="UTF-8"?>
<Root xmlns:tns="http://www.example.org/book" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.example.org/book test.xsd ">
    <Class name="AirwayBill">
        <Attribute name="billNo" primary="true" />
        <Attribute name="date" primary="false" />
        <Attribute name="shipper" primary="false" class="Person" />
        </Class>
    <Class name="Person">
        <Attribute name="perId" primary="true" />
        <Attribute name="fname" primary="false" />
        <Attribute name="lname" primary="false" />
    </Class>
</Root>

I want to read attribute value of attribute "name" of Tag in which attribute "class" is present.. how do i do that? i am using javax.xml.parsers.DocumentBuilder and javax.xml.parsers.DocumentBuilderFactory classes to parse and read the xml file.

  • Use XPath. It will help you at what you want to do. See http://stackoverflow.com/questions/2811001/how-to-read-xml-using-xpath-in-java for more information. You should first check with XPath for all 's with class="", store them in a list and then iterate over the list again to now read out the name="". –  Aug 11 '14 at 09:08
  • no i can't use XPath in my application. is there any other way by which v can do it? – Sharmishtha Kulkarni Aug 11 '14 at 09:17

1 Answers1

0

Probably there is a better way to do it, but this works:

public static void parseXml(){
    File fXmlFile = new File("c://test.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        doc.getDocumentElement().normalize();
        Element root = doc.getDocumentElement();
        NodeList childList = root.getElementsByTagName("Class");
        for (int i = 0; i<childList.getLength(); i++){
            System.out.println("Class: " + childList.item(i).getAttributes().getNamedItem("name").getNodeValue());

            NodeList attList = ((Element)childList.item(i)).getElementsByTagName("Attribute");
            for (int j = 0; j<attList.getLength(); j++){
                System.out.print("  Att: " + attList.item(j).getAttributes().getNamedItem("name").getNodeValue());
                System.out.println(" primary " + attList.item(j).getAttributes().getNamedItem("primary").getNodeValue());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
agamesh
  • 559
  • 1
  • 10
  • 26