如何使用Annotations(Java)从XML中的内部节点读取字符串

时间:2017-07-14 11:58:34

标签: java xml annotations

我必须使用javax.xml.bind.annotation库中的注释在java中编写一个Config-Reader。问题是我真的不知道如何到达内部节点(在我的情况下是mailConfig)。这是我的XML文件的格式:

 <?xml version="1.0" encoding="UTF-8">
 <config>
   <avoidanceList>
      <avoid> item1 </avoid>
      <avoid> item2 </avoid>
   </avoidanceList>

   <ignoreList>
      <ignore> item1 </ignore>
   </ignoreList>

   <mailConfig>
     <from> From </from>

     <toList>
        <to> To1 </to>
        <to> To2 </to>
     </toList>

   </mailConfig>
</config>

我可以在avoidanceList和ignoreList中读取,但我的代码无法在整个mailConfig中读取。我在某处读到了两个类可以解决问题,但事实并非如此。这是我的读者代码:

@XmlRootElement(name = "config")
public final class Cfg {
  private List<String> avoidanceList;
  private List<String> ignoreList;

  private MailConfig mailConfig;

  @XmlElementWrapper(name = "avoidanceList")
  @XmlElement(name = "avoid", required = false)
  public List<String> getAvoidanceList() { 
      return avoidanceList; 
  }

  @XmlElementWrapper(name = "ignoreList")
  @XmlElement(name = "ignore", required = false)
  public List<String> getIgnoreList() { 
      return ignoreList; 
  }

  @XmlElements({
      @XmlElement(name="from", type=String.class),
      @XmlElement(name="to", type=String.class)})
  public MailConfig getMailConfig() {
      return mailConfig;
  } 
}

这里是MailConfig类:

@XmlRootElement(name = "mailConfig")
public class MailConfig {

  private String from;
  private List<String> toList;

  public MailConfig(String from, List<String> toList) {
      this.from = from;
      this.toList = toList;
  }

  @XmlElement(name = "from", required = false)
  public String getFrom() {
      return from;
  }

  @XmlElementWrapper(name = "toList")
  @XmlElement(name = "to", required = false)
  public List<String> getToList() { 
      return toList; 
  }
}

这是我第一次使用java中的XML文件,所以我知道代码可能完全错误。我还没有找到带注释的解决方案,所以如果有人能帮助我,这将是很棒的:)

提前致谢!

1 个答案:

答案 0 :(得分:1)

试试这个,对我有用:

@font-face {
  font-family: 'Glyphicons Halflings';

  src: url('../fonts/glyphicons-halflings-regular.eot');
  src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff2') format('woff2'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
}