Java XML Tutorial
Selected Reading
- Java XML - Discussion
- Java XML - Useful Resources
- Java XML - Quick Guide
- Java XML - Questions and Answers
- Modify XML Document
- Create XML Document
- Query XML Document
- Parse XML Document
- Java DOM4J Parser
- Modify XML Document
- Create XML Document
- Query XML Document
- Parse XML Document
- Java XPath Parser
- Modify XML Document
- Create XML Document
- Query XML Document
- Parse XML Document
- Java StAX Parser
- Modify XML Document
- Create XML Document
- Query XML Document
- Parse XML Document
- JDOM XML Parser
- Modify XML Document
- Create XML Document
- Query XML Document
- Parse XML Document
- Java SAX Parser
- Modify XML Document
- Create XML Document
- Query XML Document
- Parse XML Document
- Java DOM Parser
- Java XML Parsers
- Java XML Overview
- Java XML Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Create XML Document
Java JDOM Parser - Create XML Document
Demo Example
在此,我们需要建立XML档案——
<?xml version = "1.0" encoding = "UTF-8"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferrari 101</carname> <carname type = "sports">Ferrari 202</carname> </supercars> </cars>
CreateXmlFileDemo.java
import java.io.IOException; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; pubpc class CreateXmlFileDemo { pubpc static void main(String[] args) { try{ //root element Element carsElement = new Element("cars"); Document doc = new Document(carsElement); //supercars element Element supercarElement = new Element("supercars"); supercarElement.setAttribute(new Attribute("company","Ferrari")); //supercars element Element carElement1 = new Element("carname"); carElement1.setAttribute(new Attribute("type","formula one")); carElement1.setText("Ferrari 101"); Element carElement2 = new Element("carname"); carElement2.setAttribute(new Attribute("type","sports")); carElement2.setText("Ferrari 202"); supercarElement.addContent(carElement1); supercarElement.addContent(carElement2); doc.getRootElement().addContent(supercarElement); XMLOutputter xmlOutput = new XMLOutputter(); // display ml xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(doc, System.out); } catch(IOException e) { e.printStackTrace(); } } }
这将产生以下结果:
<?xml version = "1.0" encoding = "UTF-8"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferrari 101</carname> <carname type = "sports">Ferrari 202</carname> </supercars> </cars>Advertisements