View Javadoc
1   /*
2    * #%L
3    * wcm.io
4    * %%
5    * Copyright (C) 2014 wcm.io
6    * %%
7    * Licensed under the Apache License, Version 2.0 (the "License");
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   *
11   *      http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   * #L%
19   */
20  package io.wcm.maven.plugins.i18n.readers;
21  
22  import java.io.File;
23  import java.io.IOException;
24  import java.util.HashMap;
25  import java.util.List;
26  import java.util.Map;
27  
28  import javax.xml.XMLConstants;
29  
30  import org.jdom2.Document;
31  import org.jdom2.Element;
32  import org.jdom2.JDOMException;
33  import org.jdom2.input.SAXBuilder;
34  
35  /**
36   * Reads i18n resources from XML files.
37   */
38  public class XmlI18nReader implements I18nReader {
39  
40    @Override
41    public Map<String, String> read(File sourceFile) throws IOException {
42      try {
43        SAXBuilder builder = new SAXBuilder();
44        builder.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
45        builder.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
46        Document doc = builder.build(sourceFile);
47        Map<String, String> map = new HashMap<>();
48        parseXml(doc.getRootElement(), map, "");
49        return map;
50      }
51      catch (JDOMException ex) {
52        throw new IOException("Unable to read XML from " + sourceFile.getAbsolutePath(), ex);
53      }
54    }
55  
56    private void parseXml(Element node, Map<String, String> map, String prefix) {
57      List<Element> children = node.getChildren();
58      for (Element child : children) {
59        String key = child.getName();
60        if (!child.getChildren().isEmpty()) {
61          parseXml(child, map, prefix + key + ".");
62        }
63        else {
64          map.put(prefix + key, child.getText());
65        }
66      }
67    }
68  
69  }