是否可以像这样解组XML文件:
<company id="bh23" name="imob">
<store>
<store-info id="2392">
<address>NYC</address>
<name>Imob's NYC 5th</name>
</store>
<products>
<product>
<name>keyboard</keyboard>
<price>2000</price>
</product>
<product>
<name>mouse</keyboard>
<price>1000</price>
</product>
</products>
</store>
<store />
</stores>
进入这样的类:
@XmlElementRoot(name = "company")
public class Company {
@XmlAttribute (name = "id")
String id;
@XmlAttribute (name = "name")
String name;
@XmlElement (name = "store")
List<Store>stores;
//all the getters and setters
}
@XmlElementRoot (name = "store")
public class Store {
@XmlAttribute (name = "id")
String id;
@XmlElement (name = "address")
String address;
@XmlElement (name = "name")
String name;
@XmlElementWrapper (name = "products")
@XmlElement (name = "product")
List<Product>products;
//all the getters and setters
}
public class main {
public static void main (String args[]) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Company.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Company portfolio = (Company) jaxbUnmarshaller.unmarshal(new File(xmlUrlPath));
System.out.println(portfolio.toString());
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
我正在尝试“跳过”或“跳转”名为“store-info”的节点,因为我不想创建另一个类只是为了保留商店的地址和名称,因为它会更简单“将“地址和名称”附加到“商店”类。 当然,当我运行代码时,变量“address”,“id”和“name”变为null,只有产品列表才能正确解组。 有没有办法跳过一个节点,将他们的字段合并到另一个类?我正在避免(出于“合法”目的)使用MOXy lib及其XPath注释。
答案 0 :(得分:1)
您可以创建一个StAX过滤的XMLStreamReader
并让JAXB解组以忽略一个或多个XML元素。
以下是我在回答类似问题时给出的完整示例的链接: