2

我有一个如下的 XML。

 <hotelRoomDetails>
  <NightRates>
   <Night1>67</Night1>
   <Night2>67.5</Night2> 
   ........
   ........
   <Night25>65</Night25> 
  </NightRates>
  .......
  </hotelRoomDetails>

元素 Night1,Night2,Night3 总是动态的,这个计数可能在 1 到 35 次之间变化。父标签<NightRates>始终是一致的。

元素<Night1>, <Night2>.. 没有任何其他属性。它提供有关每晚酒店价格的信息。

我想创建一个包含单个夜晚价格信息的“LinkedList”(以保留订单)。在不知道元素出现次数的情况下如何处理这种情况?如何为这个xml创建java类?

4

2 回答 2

2

您可以将 NightRates 字段设为任何类型。并通过 org.w3c.dom.Element 处理其内容:

@XmlAnyElement
protected Element NightRates;
于 2013-11-07T11:59:54.623 回答
1

仅解组

如果您只是在进行解组,那么您可以使用 aStreamReaderDelegate去除数字后缀。

演示

import javax.xml.bind.*;
import javax.xml.stream.*;
import javax.xml.stream.util.StreamReaderDelegate;
import javax.xml.transform.stream.StreamSource;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(HotelRoomDetails.class);

        XMLInputFactory xif = XMLInputFactory.newFactory();
        XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource("src/forum19834756/input.xml"));
        xsr = new StreamReaderDelegate(xsr) {
            @Override
            public String getLocalName() {
                String localName = super.getLocalName();
                if(localName.startsWith("Night") && !localName.equals("NightRates")) {
                    return "Night";
                }
                return localName;
            }

        };

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        HotelRoomDetails details = (HotelRoomDetails) unmarshaller.unmarshal(xsr);
        System.out.println(details.getNightRates().size());
    }

}

酒店客房详情

Then you have a collection property that maps to the element called Night.

import java.util.*;
import javax.xml.bind.annotation.*;

@XmlRootElement
public class HotelRoomDetails {

    private List<String> nightRates = new ArrayList<String>();

    @XmlElementWrapper(name = "NightRates")
    @XmlElement(name = "Night")
    public List<String> getNightRates() {
        return nightRates;
    }

}

Unmarshal & Marshal

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.

If you need to support reading and writing to this format you could use MOXy's @XmlVariableNode extension.

于 2013-11-18T21:13:19.193 回答