有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用googlehttpclientxml解析xml:使用XmlObjectParser解析xml元素内容和属性

我似乎无法解析以下xml中的值。如果我使用的是GoogleHTTPJava客户端,那么解析xml类型的解析器类是什么?下面是示例xml和解析器

<feed>
  <text start="1" end="10"> Text 1 </text> 
  <text start="2" end="20"> Text 2 </text> 
  <text start="3" end="30"> Text 3 </text> 
  <text start="4" end="40"> Text 4 </text> 
  <text start="5" end="50"> Text 5 </text> 
</feed>

Class Feed {
 @Key("text")
 public List<Text> textList;
}

Class Text {
  @Key("@start")
  public String startTime;


  @Key("@end")
  public String endTime; 
}

为了清楚起见,我需要开始属性值、结束属性值和文本内容。似乎有效的方法如下

HttpRequestFactory httpRequestFactory =
        HTTP_TRANSPORT.createRequestFactory(
            new HttpRequestInitializer() {
              @Override
              public void initialize(HttpRequest request) throws IOException {
                request.setParser(new XmlObjectParser(new XmlNamespaceDictionary().set("", "")));
              }
            });    
Feed feedObject = httpResponse.parseAs(Feed.class);

但我无法获得内容值

如果我将feed类更改为

Class Feed {
     @Key("text")
     public List<String> textList;
}

我只能得到内容,不能得到属性值

任何示例源代码都很难找到(在github、stackoverflow等上)


共 (1) 个答案

  1. # 1 楼答案

    好的,这里是通过github梳理后的答案

    <feed>
      <text start="1" end="10"> Text 1 </text> 
      <text start="2" end="20"> Text 2 </text> 
      <text start="3" end="30"> Text 3 </text> 
      <text start="4" end="40"> Text 4 </text> 
      <text start="5" end="50"> Text 5 </text> 
    </feed>
    
    Class Feed {
     @Key("text")
     public List<Text> textList;
    }
    
    Class Text {
      @Key("@start")
      public String startTime;
    
      @Key("@end")
      public String endTime; 
    
      @Key("text()")
      public String payload; 
    }