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);
}
} }
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With