在Java中使用XML:流畅的XSD,无需解析

时间:2011-08-25 10:47:24

标签: java xml xsd

有没有人知道在Java中使用符合这些要求的XML的解决方案?

  • 能够流畅地定义XML架构(没有XSD)
  • 能够通过Java标准类型处理XML数据:如果我说这个标记的这个属性是一个整数,我希望能够以int的形式读取和写入它,而无需解析和转换它是手动字符串。

理想的解决方案是这样的:

class MyXmlData { 
  @Bind("...xpath here...", Bind.Required)
  public Integer numberOfPersons; // required, integer

  @Bind("...xpath here...")
  public String title; // optional 
}

try { // throws, if required fields are not present
  MyXmlData data = MagicXml.read(MyXmlData.class, "1.xml");

  // at this point data.numberOfPersons is never null and
  // title may be null

  int myNumOfPersons = data.numberOfPersons; // here we go
}

2 个答案:

答案 0 :(得分:2)

结帐EclipseLink JAXB (MOXy)。我们的@XmlPath注释类似于您要查找的@Bind注释:

package blog.geocode;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlRootElement(name="kml")
@XmlType(propOrder={"country", "state", "city", "street", "postalCode"})
public class Address {

    @XmlPath("Response/Placemark/ns:AddressDetails/ns:Country/ns:AdministrativeArea/ns:SubAdministrativeArea/ns:Locality/ns:Thoroughfare/ns:ThoroughfareName/text()")
    private String street;

    @XmlPath("Response/Placemark/ns:AddressDetails/ns:Country/ns:AdministrativeArea/ns:SubAdministrativeArea/ns:Locality/ns:LocalityName/text()")
    private String city;

    @XmlPath("Response/Placemark/ns:AddressDetails/ns:Country/ns:AdministrativeArea/ns:AdministrativeAreaName/text()")
    private String state;

    @XmlPath("Response/Placemark/ns:AddressDetails/ns:Country/ns:CountryNameCode/text()")
    private String country;

    @XmlPath("Response/Placemark/ns:AddressDetails/ns:Country/ns:AdministrativeArea/ns:SubAdministrativeArea/ns:Locality/ns:PostalCode/ns:PostalCodeNumber/text()")
    private String postalCode;

}

了解更多信息

答案 1 :(得分:1)