如何使用JAXB将空标记解析为标记元素的名称而不是空字符串的值?

问题描述:

我有一个输入XML文件,它使用空标记来表示有效的数据。我无法改变这一点。物品材料可以是由空标签<metal/><plastic/>指定的“金属”或“塑料”。 JAXB的问题在于它将空标签解组为空字符串。如何使用JAXB以便我可以提取<metal/><plastic/>作为它们的xml标记名称,字符串"metal""plastic"而不是它们的空值?如果没有办法使用JAXB来完成,我应该使用哪种解析器?如何使用JAXB将空标记解析为标记元素的名称而不是空字符串的值?

XML输入文件

<items> 
    <item> 
     <id>item 1<id> 
     <material> 
      <metal/> 
     </material> 
    </item> 
    <item> 
     <id>item 2<id> 
     <material> 
      <plastic/> 
     </material> 
    </item> 
</items> 

Java bean类对应的Java对象。

@XmlRootElement(name = "items") 
public class Items{ 
    private List<Item> items; 


    public List<Item> getItems() { 
     return items; 
    } 

    @XmlElement(name = "item") 
    public void setItes(List<Item> items) { 
     this.items= items; 
    } 

    public static class Item{ 

     private String  id; 
     private String  material; 



     public String getId() { 
      return id; 
     } 

     @XmlElement(name = "id") 
     public void setId(String id) { 
      this.id = id; 
     } 

     public String getMaterial() { 
       return material; 
     } 

     @XmlElement 
     public void setMaterial(String material) { 
       this.material = material; 
     } 

Controller类

public class ItemParser { 

    public static void main(String[] args) { 
    // System.out.println("Hello World!"); 


     try { 

      File file = new File("I:\\items.xml"); 
      JAXBContext jaxbContext = JAXBContext.newInstance(Items.class); 

      Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); 
      Items items = (Items) jaxbUnmarshaller.unmarshal(file); 


      } catch (JAXBException e) { 
      e.printStackTrace(); 
      } 

    } 
} 

你必须定义另一个类命名的材料和类中需要定义金属和塑料

+0

我试过张贴问题,但该方法止跌”之前因为在这种情况下,JAXB将视为空标记。因此,它将Java类的字段设置为空字符串。我试图使用位置侦听器,但是这种方法也不起作用。我结束了使用DOM解析器,它允许我解析出一个空标签的名称。 – AlexG