0

我有几本书的参考必须转换为 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 格式?
你有什么建议?

4

2 回答 2

2

例如,使用 JAXB。

  1. 获取XSD您想要的XML格式。
  2. 生成 java 类XSD- 看这里如何。
  3. 实现一个简单的程序,该程序将解析您的输入文件并在生成的类的帮助下构建一棵树。根据您的输入,这可能是微不足道的或非常困难的。
  4. 序列化结果 - 看看这里如何。

编辑:正如 Joop Eggen 所暗示的,您也可以使用注释而不是步骤 1-3。这可能使事情变得更简单。看看这里如何。

于 2013-07-05T12:48:17.393 回答
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);
}
于 2013-07-05T13:23:23.487 回答