(Step 3)JDOM操作XML之(Sonnet示例)

来源:互联网 发布:mac 搭建软件开发环境 编辑:程序博客网 时间:2024/06/05 01:10

读取sonnet文件,然后以流的方式输出。注意,除了sonnet.xml还要定义sonnet.dtd文件。(关于xml的相关信息,在以后的文章中会涉及)

 

public class JdomOne
{
  public static void main(String[] argv)
  {
    try
    {
      SAXBuilder sb = new SAXBuilder();
      Document doc = sb.build(new File("sonnet.xml"));
      XMLOutputter xo = new XMLOutputter();

      xo.setTrimAllWhite(true); //去除所有空格回车
      xo.output(doc, System.out);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
}

 

 

---sonnet.xml---

 

<?xml version="1.0"?>
<!DOCTYPE sonnet SYSTEM "sonnet.dtd">
<sonnet type="Shakespearean">
  <author>
    <lastName>Shakespeare</lastName>
    <firstName>William</firstName>
    <nationality>British</nationality>
    <yearOfBirth>1564</yearOfBirth>
    <yearOfDeath>1616</yearOfDeath>
  </author>
  <title>Sonnet 130</title>
  <lines>
    <line>My mistress' eyes are nothing like the sun,</line>
    <line>Coral is far more red than her lips red.</line>
    <line>If snow be white, why then her breasts are dun,</line>
    <line>If hairs be wires, black wires grow on her head.</line>
    <line>I have seen roses damasked, red and white,</line>
    <line>But no such roses see I in her cheeks.</line>
    <line>And in some perfumes is there more delight</line>
    <line>Than in the breath that from my mistress reeks.</line>
    <line>I love to hear her speak, yet well I know</line>
    <line>That music hath a far more pleasing sound.</line>
    <line>I grant I never saw a goddess go,</line>
    <line>My mistress when she walks, treads on the ground.</line>
    <line>And yet, by Heaven, I think my love as rare</line>
    <line>As any she belied with false compare.</line>
  </lines>

</sonnet>

 

 

---sonnet.dtd-----

 

<!-- sonnet.dtd                                        -->

<!-- sonnet is the root of the document                -->
<!ELEMENT sonnet  (author,title?,lines)>
<!-- the default sonnet type is "Shakespearean"        -->
<!ATTLIST sonnet  type (Shakespearean | Petrarchan) 
                       "Shakespearean">

<!-- author contains information about the author      -->
<!ELEMENT author  (lastName,firstName,nationality,
                   yearOfBirth?,yearOfDeath?)>

<!-- lastName, firstName, nationality, yearOfBirth,
     and yearOfDeath are all elements inside author. -->

<!ELEMENT lastName (#PCDATA)>
<!ELEMENT firstName (#PCDATA)>
<!ELEMENT nationality (#PCDATA)>
<!ELEMENT yearOfBirth (#PCDATA)>
<!ELEMENT yearOfDeath (#PCDATA)>

<!-- The title of the sonnet                           -->
<!ELEMENT title (#PCDATA)>

<!-- The lines element contains the 14 lines of the   
     sonnet.                                           -->
<!ELEMENT lines (line,line,line,line,
                 line,line,line,line,
                 line,line,line,line,
                 line,line)>

<!ELEMENT line (#PCDATA)>

 

原创粉丝点击