开发者

XML Schema for SimpleType and Attribute?

I'm trying to create an XML schema that can capture XML that looks something like this:

<tagname description="simple string type attribute">
false <!-- simple boolean type -->
</tagname>

But am running into difficulties. Is it even possible to define a schema to capture this or am I on开发者_JAVA百科 a snipe hunt?


Here you go

<xs:element name="tagname">
        <xs:complexType>
            <xs:simpleContent>
                <xs:extension base="xs:boolean">
                    <xs:attribute name="description" type="xs:string" use="required"/>
                </xs:extension>
            </xs:simpleContent>
        </xs:complexType>
    </xs:element>

And here is the validated sample

<tagname xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="file:/C:/Untitled2.xsd" description="123">
    true
</tagname>


Thank you, thank you, thank you. I've been struggling with this problem for a while and it is not really that obvious how to define the schema even though the actual XML sample is pretty straight forward. My biggest problem was in how to structure a JAXB class to handle this. It was only until I saw your schema definition and ran it through xjc that I was able to see how to set it up in JAXB. The JAXB java classes are pretty un-intuitive IMHO and I would have never guessed how to set it up. I've tried several different ways of getting this to work without any success.

Below is a sample of the JAXB java class that gets generated from your posted schema. The key is using the the @XmlValue annotation on the field (you can also use it on the getter of the field but remove the XmlAccessorType annotation:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "value" })
@XmlRootElement(name = "tagname")
public class Tagname {

  @XmlValue
  protected boolean value;
  @XmlAttribute(name = "description", required = true)
  protected String  description;

  public boolean isValue() {
    return value;
  }

  public void setValue(boolean value) {
    this.value = value;
  }

 get and set for description omitted.

Here is the marshalled JAXB XML document from the given class:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<tagname description="The Description">true</tagname>

I hope this addition will help others who are struggling with the same obscure problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜