【问题标题】:JAXB default attribute valueJAXB 默认属性值
【发布时间】:2011-12-16 02:23:45
【问题描述】:

我正在使用 JAXB 注释从我的类生成 xsd 架构。

带有参数defaultValue 的注解@XmlElement 设置元素的默认值。 是否可以为@XmlAttribute 设置默认值?

附:我检查了 xsd 语法是否允许属性的默认值

【问题讨论】:

  • 什么...注释实际上没有一些 defaultValue 键。我其实很惊讶。
  • 已经讨论了元素的默认值here——也许会对你的属性有所帮助。

标签: java xml xsd jaxb


【解决方案1】:

可能想检查一下:Does JAXB support default schema values?

说实话,我不知道为什么标准 JAXB 中没有属性默认选项。

【讨论】:

    【解决方案2】:

    当您从 xsd 生成类时,您在其中定义了具有默认值的属性,然后 jaxb 将生成一个 if 子句,它将检查 null 值,如果是,则返回默认值。

    【讨论】:

      【解决方案3】:

      对于 XML 属性,默认值放在 getter 方法中。

      例如,

      customer.xsd

      <?xml version="1.0" encoding="UTF-8"?>
      <schema xmlns="http://www.w3.org/2001/XMLSchema">
          <element name="Customer">
              <complexType>
                  <sequence>
                      <element name="element" type="string" maxOccurs="1" minOccurs="0" default="defaultElementName"></element>
                  </sequence>
                  <attribute name="attribute" type="string" default="defaultAttributeValue"></attribute>
              </complexType>
          </element>
      </schema>
      

      它将生成如下所示的类。

      @XmlRootElement(name = "Customer")
      public class Customer {
      
          @XmlElement(required = true, defaultValue = "defaultElementName")
          protected String element;
          @XmlAttribute(name = "attribute")
          protected String attribute;
      
          ......
      
          public String getAttribute() {
              //here the default value is set.
              if (attribute == null) {
                  return "defaultAttributeValue";
              } else {
                  return attribute;
              }
          }
      

      创建了要读取的示例 XML

      <?xml version="1.0" encoding="UTF-8" standalone="yes"?><Customer><element/></Customer>
      

      当我们在主类中编写逻辑编组时。

      File file = new File("...src/com/testdefault/xsd/CustomerRead.xml");
                  JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
      
                  Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                  Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
                  System.out.println(customer.getElement());
                  System.out.println(customer.getAttribute());
      

      它将在控制台中打印。 默认元素名称 默认属性值

      P.S -:要获取元素的默认值,您需要将元素的空白副本放入正在编组的 xml 中。

      【讨论】:

        猜你喜欢
        • 2023-03-18
        • 1970-01-01
        • 2011-08-19
        • 1970-01-01
        • 1970-01-01
        • 2010-10-16
        • 2012-01-05
        • 2020-08-16
        相关资源
        最近更新 更多