我有一個XML文件,元素也有屬性。 我有一個簡單的java文件,它解析和打印文本文件中的元素值,但不包含元素屬性值。 請幫助您獲取要打印的屬性值。 我粘貼下面的代碼: -------- employees.xml文件-----------使用Java解析XML並獲取元素值和屬性值
<?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);
}
} }
見鏈接http://stackoverflow.com/questions/9781568/update-data-in-java-class-as -per變化,在屬性 - 在最XML的文件/ 9783154#9783154 – 2012-03-20 09:14:44