Java @XmlElement 和无用的“必需”参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19266391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 15:33:47  来源:igfitidea点击:

@XmlElement and useless 'required' parameter

javajaxb

提问by

I put @XmlElement(name = "title",required = true)before the javabean property int some_property, and didn't assign a value to some_property. For some reason this property is not occurred in generated XML. So, please, explain the meaning of required

我将 @XmlElement(name = "title",required = true)放在 javabean 属性 int some_property 之前,并且没有为some_property 赋值。出于某种原因,此属性未出现在生成的 XML 中。所以,请解释required的含义

some meaningful parts of the code:

代码的一些有意义的部分:

@XmlRootElement(name = "book")
@XmlType(propOrder = { "author", "name", "publisher", "isbn" })
public class Book {

private String name;
private String author;
private String publisher;
private String isbn;

// If you like the variable name, e.g. "name", you can easily change this
// name for your XML-Output:
@XmlElement(name = "title",required = true)
public String getName() {
    return name;
}
....

Somewhere int the Main:

某处主要的

    // create books
    Book book1 = new Book();
    book1.setIsbn("978-0060554736");

    book1.setAuthor("Neil Strauss");
    book1.setPublisher("Harpercollins");
    bookList.add(book1);


    Book book2 = new Book();
    book2.setIsbn("978-3832180577");
    book2.setName("Feuchtgebiete");
    book2.setAuthor("Charlotte Roche");
    book2.setPublisher("Dumont Buchverlag");
    bookList.add(book2);

    JAXBContext context = JAXBContext.newInstance(Bookstore.class);
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

    // Write to System.out
    m.marshal(bookstore, System.out);

    // Write to File
    m.marshal(bookstore, new File(BOOKSTORE_XML));

    // get variables from our xml file, created before
    System.out.println();
    System.out.println("Output from our XML File: ");
    Unmarshaller um = context.createUnmarshaller();
    Bookstore bookstore2 = (Bookstore) um.unmarshal(new FileReader(BOOKSTORE_XML));
    ArrayList<Book> list = bookstore2.getBooksList();

采纳答案by bdoughan

What requiredDoes on @XmlElement

有什么required作用@XmlElement

The requiredproperty on the @XmlElementannotation affects the XML schema that is generated from Java classes.

required对房地产@XmlElement注释影响从Java类生成的XML架构。

Domain Model (Root)

域模型(根)

Below is a simple Java model. Note how the barproperty has required=trueand the fooproperty does not.

下面是一个简单的 Java 模型。请注意该bar属性如何具有required=true和该foo属性没有。

import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {

    @XmlElement
    private String foo;

    @XmlElement(required=true)
    private String bar;

    @XmlElement(nillable=true)
    private String baz;

}

Demo Code

演示代码

Below is some code that demonstrates how to generate an XML schema using the JAXBContext.

下面是一些演示如何使用 .xml 文件生成 XML 模式的代码JAXBContext

import java.io.IOException;
import javax.xml.bind.*;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;

public class GenerateSchema {

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

        jc.generateSchema(new SchemaOutputResolver() {
            @Override
            public Result createOutput(String namespaceUri,
                    String suggestedFileName) throws IOException {
                StreamResult result = new StreamResult(System.out);
                result.setSystemId(suggestedFileName);
                return result;
            }
        });
    }

}

Generated XML Schema

生成的 XML 模式

Below is the resulting XML schema note how the XML element corresponding to the foofield has minOccurs="0"while the XML element corresponding to the barfield (which was annotated with @XmlElement(required=true)does not. This is because the default minOccursis 1 meaning it's required.

下面是生成的 XML 模式注释,与该foo字段对应的 XML 元素如何,minOccurs="0"而与该bar字段对应的 XML 元素(注释为@XmlElement(required=true)没有。这是因为默认minOccurs值为 1 表示它是必需的。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="root" type="root"/>
  <xs:complexType name="root">
    <xs:sequence>
      <xs:element name="foo" type="xs:string" minOccurs="0"/>
      <xs:element name="bar" type="xs:string"/>
      <xs:element name="baz" type="xs:string" nillable="true" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

If You Want an Element for nullValues

如果您想要null值的元素

Domain Model (Root)

域模型(根)

The bazfield has been annotated with @XmlElement(nillable=true). If the value is null the resulting XML element will leverage the xsi:nilattribute. Without this annotation null values will be treated as absent nodes.

baz字段已用 注释@XmlElement(nillable=true)。如果值为 null,则生成的 XML 元素将利用该xsi:nil属性。如果没有此注释,空值将被视为不存在的节点。

import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {

    @XmlElement
    private String foo;

    @XmlElement(required=true)
    private String bar;

    @XmlElement(nillable=true)
    private String baz;

}

Demo Code

演示代码

import javax.xml.bind.*;

public class MarshalDemo {

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

        Root root = new Root();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }

}

Output

输出

Below is the resulting XML from running the demo code.

下面是运行演示代码的结果 XML。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <baz xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
</root>

回答by michal

Could you show us a sample of your code and generated xml? According to docs:

您能否向我们展示您的代码示例和生成的 xml?根据文档:

If required is true, then Javabean property is mapped to an XML schema element declaration with minOccurs="1". maxOccurs is "1" for a single valued property and "unbounded" for a multivalued property.

如果 required 为 true,则 Javabean 属性将映射到 minOccurs="1" 的 XML 模式元素声明。maxOccurs 对于单值属性为“1”,对于多值属性为“unbounded”。

回答by Norw?

From: http://docs.oracle.com/javaee/5/api/javax/xml/bind/annotation/XmlElement.html

来自:http: //docs.oracle.com/javaee/5/api/javax/xml/bind/annotation/XmlElement.html

public abstract boolean required

Customize the element declaration to be required. If required() is true, then Javabean property is mapped to an XML schema element declaration with minOccurs="1". maxOccurs is "1" for a single valued property and "unbounded" for a multivalued property.

If required() is false, then the Javabean property is mapped to XML Schema element declaration with minOccurs="0". maxOccurs is "1" for a single valued property and "unbounded" for a multivalued property.

需要公共抽象布尔值

自定义需要的元素声明。如果 required() 为 true,则 Javabean 属性将映射到 minOccurs="1" 的 XML 模式元素声明。maxOccurs 对于单值属性为“1”,对于多值属性为“unbounded”。

如果 required() 为 false,则 Javabean 属性将映射到 minOccurs="0" 的 XML 模式元素声明。maxOccurs 对于单值属性为“1”,对于多值属性为“unbounded”。

Your property is mapped to an element that is (hopefully) declared as required in the schema. Your generated XML is not compliant to that particular schema, which is more or less what I expected from an instance that does not "play by the rules" it has laid out

您的属性映射到(希望)根据架构中的要求声明的元素。您生成的 XML 不符合该特定模式,这或多或少是我对不“遵守规则”的实例所期望的