Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a single XML element have multiple values?

Tags:

xml

xsd

A product can comply with zero or several standards, eg STD1, STD2, STD3.

The XML has a optional field, let's call it complies.

Can I make something like that? (Here I use a comma.)

<complies>STD1,STD3</complies> or <complies>STD2</complies>

And how can I define this XSD type?

like image 612
Minstrel Avatar asked May 12 '15 13:05

Minstrel


People also ask

Can XML attribute have multiple values?

attributes cannot contain multiple values (elements can) attributes cannot contain tree structures (elements can) attributes are not easily expandable (for future changes)

Can XML elements have multiple attributes with same name?

You can't. Attribute names are unique per element.

How many attributes can XML have?

Rules for XML attributes XML element can have more than one attributes. This we have already seen in the above example, where brand and category attributes are linked to the element <car>. 3. Attributes cannot contain duplicate multiple values.


1 Answers

The right way to design the XML structure for an element that has multiple values would be to individually tag each such value, standard elements in this case:

<complies>
  <standard>STD1</standard>
  <standard>STD2</standard>
</complies>

This will allow XML schemas (XSD, DTDs, etc) to validate directly. Here's the trivial XSD for such structure:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="complies">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="standard" minOccurs="0" maxOccurs="unbounded">
          <xs:simpleType>
            <xs:restriction base="xs:string">
              <xs:enumeration value="STD1"/>
              <xs:enumeration value="STD2"/>
              <xs:enumeration value="STD3"/>
            </xs:restriction>
          </xs:simpleType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

This approach will also allow you to leverage XML parsers directly and thereby avoid having to micro-parse the complies element.


Update

Alternatively, if you don't want to introduce a separate standard element,

<complies>STD1 STD2</complies>

you could use XSD's xs:list construct:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="complies">
    <xs:simpleType>
      <xs:list>
        <xs:simpleType>
          <xs:restriction base="xs:string">
            <xs:enumeration value="STD1"/>
            <xs:enumeration value="STD2"/>
            <xs:enumeration value="STD3"/>
          </xs:restriction>
        </xs:simpleType>
      </xs:list>
    </xs:simpleType>
  </xs:element>
</xs:schema>

Thanks to John Saunders for this helpful suggestion.

like image 143
kjhughes Avatar answered Sep 30 '22 02:09

kjhughes