如何通过jaxb从生成的XML中删除不需要的元素 [英] How to remove not required Elements from generated XML via jaxb

查看:89
本文介绍了如何通过jaxb从生成的XML中删除不需要的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有使用jaxb从生成的xml中删除不需要的元素。我的xsd元素定义如下。

I want to know if there is anyway for removing not required elements from generated xml using jaxb.I have my xsd element definition as follows.

           <xsd:element name="Title" maxOccurs="1" minOccurs="0">
                <xsd:annotation>
                    <xsd:documentation>
                        A name given to the digital record.
                    </xsd:documentation>
                </xsd:annotation>
                <xsd:simpleType>
                    <xsd:restriction base="xsd:string">
                        <xsd:minLength value="1"></xsd:minLength>
                    </xsd:restriction>
                </xsd:simpleType>
            </xsd:element>

正如您所看到的那样,它不是必需元素,因为

As you can see it is not a mandatory element because


minOccurs =0

minOccurs="0"

但如果它不为空,则长度应为1。

But if it is not empty the length should be 1.

<xsd:minLength value="1"></xsd:minLength>

在编组时,如果我将标题字段留空,则抛出
SAXException 因为长度限制。
所以我想要做的是从生成的XML中删除整个< Title />
。现在我删除了最小长度限制,因此它将< Title> 元素添加为 EMPTY

At the time of marshalling if I left the Title field blank it is throwing the SAXException because of min-length restriction. So what I want to do is to remove the whole occurrence of <Title/> from generated XML.Right now i have removed the min-length restriction so it is adding the <Title> element as EMPTY

<Title></Title>

但我不希望它像这样。感谢任何帮助。我正在使用jaxb 2.0进行编组。

But I do not want it like this.Any help is appreciated.I am using jaxb 2.0 for Marshalling.

更新:

以下是我的变量定义:

  private JAXBContext jaxbContext;
    private Unmarshaller unmarshaller;
    private SchemaFactory factory;
    private Schema schema;
    private Marshaller marshaller;

编组代码。

            jaxbContext = JAXBContext.newInstance(ERecordType.class);
            marshaller = jaxbContext.createMarshaller();
            factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            schema = factory.newSchema((new File(xsdLocation)));
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            ERecordType e = new ERecordType();
            e.setCataloging(rc);
            /**
             * Validate Against Schema.
             */
            marshaller.setSchema(schema);
            /**
             * Marshal will throw an exception if XML not validated against
             * schema.
             */
            marshaller.marshal(e, System.out);


推荐答案

如果将标题值设置为空字符串如果将其设置为 null,它将生成< Title /> 它应该完全省略该元素。

If you set the title value to the empty string "" it'll generate <Title/>, if you set it to null it should omit the element entirely.

这篇关于如何通过jaxb从生成的XML中删除不需要的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆