我如何开始用Java编写这个XML?

时间:2015-03-01 03:17:39

标签: java xml

<?xml version="1.0"?>
<!-- Course information -->
<courses>

I don't know how to do this

<course number=" CIS 101">
<title>Personal Computing</ title >
</course>
<course number=" CIS 234">
<title>Introduction to Java Programming</ title >
<prerequisites>
<prerequisite>CIS 101</prerequisite >
<prerequisite>STA 120</prerequisite >
</prerequisites>
</course>
<course number="CIS 304">
<title>Intermediate Java Programming</ title >
<prerequisites>
<prerequisite>CIS 234</prerequisite >
</prerequisites>
</course>
</courses> 

1 个答案:

答案 0 :(得分:0)

您可以使用作为Java SE 6及更高版本的一部分提供的StAX API来创建XML文档:

XMLOutputFactory xof = XMLOutputFactory.newFactory();
XMLStreamWriter xsr = xof.createXMLStreamWriter(System.out);
xsw.writeStartDocument();
xsw.writeStartElement("courses");
xsw.writeStartElement("course");
xsw.writeAttribute("number", " CIS 101");
xsw.writeStartElement("title");
xsw.writeCharacters("Personal Computing");
xsw.writeEndElement();  // </title>
...
xsw.writeEndElement(); // </course>
xsw.writeEndElement(); // </courses>
xsw.writeEndDocument();