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);
}
} }
What you are using is an XSLT transformation which by default transforms to element texts.
Using the same technique, one needs an own "stylesheet":
Above I used a resource, not a file system File, so it is packed with the application.
employees.xslt:
Which would produce:
Since you are using org.w3c.dom you might use the following: