如何将book的引用转换为XML?

时间:2013-07-05 12:43:27

标签: java xml xml-binding oxm

我有几本书的参考必须转换为XML 我想用Java为这个动作创建应用程序。

书的参考:

 Schulz V, Hansel R, Tyler VE. Rational phytotherapy: a physician's guide to herbal   
 medicine. 3rd ed., fully rev. and expand. Berlin: Springer; c1998. 306 p.


XML:

<element-citation publication-type="book" publication-format="print">
    <name>
        <surname>Schulz</surname>
        <given-names>V</given-names>
    </name>
    <name>
        <surname>Hansel</surname>
        <given-names>R</given-names>
    </name>
    <name>
        <surname>Tyler</surname>
        <given-names>VE</given-names>
    </name>
    <source>Rational phytotherapy: a physician's guide to herbal medicine</source>
    <edition>3rd ed., fully rev. and expand</edition>
    <publisher-loc>Berlin</publisher-loc>
    <publisher-name>Springer</publisher-name>
    <year>c1998</year>
    <size units="page">306 p</size>
</element-citation>


如何将图书的引用转换为XML格式?
你有什么建议?

2 个答案:

答案 0 :(得分:2)

例如,使用JAXB。

  1. 获取所需XSD格式的XML
  2. XSD生成java类 - 请参阅here
  3. 实现一个简单的程序,它将解析您的输入文件,并在生成的类的帮助下构建一个树。根据您的意见,这可能很简单或非常困难。
  4. 序列化结果 - 请参阅here
  5. 编辑:正如Joop Eggen所暗示,您也可以使用注释代替步骤1-3。这使得事情可能更简单。了解here

    的方式

答案 1 :(得分:0)

您可能没有Java经验,这是一个枯燥,简单的解决方案(Java 7):

  • 将XML写为文本;
  • 使用String.split(regex)解析(Scanner也会这样做。)

请注意,bookref文本中的特殊字符< > & " '可能需要替换为  &lt; &gt; &amp; &quot; &apos;

String bookRef = "Schulz V, Hansel R, Tyler VE. Rational phytotherapy: a physician's guide to herbal "
        + "medicine. 3rd ed., fully rev. and expand. Berlin: Springer; c1998. 306 p.";

File file = new File("D:/dev/xml-part.txt");
final String TAB = "    ";
try (PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")))) {
    out.println(TAB + "<element-citation publication-type=\"book\" publication-format=\"print\">");

    String[] lines = bookRef.split("\\.\\s*");

    String names = lines[0];
    String[] nameArray = names.split(",\\s*");
    for (String name : nameArray) {
        String[] nameParts = name.split(" +", 2);
        out.println(TAB + TAB + "<name>");
        out.println(TAB + TAB + TAB + "<surname>" + nameParts[0] + "</surname>");
        out.println(TAB + TAB + TAB + "<given-name>" + nameParts[1] + "</given-name>");
        out.println(TAB + TAB + "</name>");
    }
    out.println(TAB + TAB + "<source>" + lines[1] + "</source>");
    ...

    out.println(TAB + "</element-citation>");
} catch (FileNotFoundException | UnsupportedEncodingException ex) {
    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}