Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML parsing using Java with getting element values and attribute values

Tags:

java

parsing

xml

i have an XML file and the elements also have attributes. I have a simple java file which is parsing and printing values of elements in a text file but not element attribute values. Please can you help in getting the attributes values also to be printed. I am pasting the code below: --------employees.xml file-----------

<?xml version="1.0" encoding="UTF-8"?>

<Personnel>

  <Employee type="permanent">
    <Name>Seagull</Name>
    <Id>3674</Id>
    <Age>34</Age>
   </Employee>

  <Employee type="contract">
    <Name>Robin</Name>
    <Id>3675</Id>
    <Age>25</Age>
</Employee>

  <Employee type="permanent">
    <Name>Crow</Name>
    <Id>3676</Id>
    <Age>28</Age>
  </Employee>

</Personnel>

----------------------------StoreData.java-----------------------------------------

import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult;

public class StoreData{
static public void main(String[] arg) {
    try{
        BufferedReader bf = new BufferedReader(new       InputStreamReader(System.in));
        System.out.print("Enter XML file name: ");
        String xmlFile = bf.readLine();
        File file = new File(xmlFile);
            if (file.exists()){
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(xmlFile);
                        //Create transformer
            Transformer tFormer = TransformerFactory.newInstance().newTransformer();
                     //Output Types (text/xml/html)
            tFormer.setOutputProperty(OutputKeys.METHOD, "text");
//              Write the document to a file
            Source source = new DOMSource(doc);
//              Create File  to view your xml data as (vk.txt/vk.doc/vk.xls/vk.shtml/vk.html)
            Result result = new StreamResult(new File("file.txt"));
            tFormer.transform(source, result);
            System.out.println("File creation successfully!");
        }
        else{
            System.out.println("File not found!");
        }
    }
    catch (Exception e){
        System.err.println(e);
        System.exit(0);
    }  
} }

like image 771
user1036204 Avatar asked Mar 18 '12 13:03

user1036204


1 Answers

Since you are using org.w3c.dom you might use the following:

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(xmlFile));
        Document doc = builder.parse(is);

        NodeList nodeList = doc.getElementsByTagName("Employee");

        for (int i = 0; i < nodeList.getLength(); i++) {                
            Node node = nodeList.item(i);

            if (node.hasAttributes()) {
                Attr attr = (Attr) node.getAttributes().getNamedItem("type");
                if (attr != null) {
                    String attribute= attr.getValue();                      
                    System.out.println("attribute: " + attribute);                      
                }
            }
        }
like image 81
stzoannos Avatar answered Oct 02 '22 16:10

stzoannos