Reputation: 677
I'm just getting started with XSD trying to validate an XML configuration file I've been using. Each configuration specifies a default configuration for a server, which can be overridden on a per-server basis.
This is the default:
<server>
<cpu>65</cpu>
// Other configuration
</server>
This is an (optional) override:
<server key="2">
<cpu>55</cpu>
</server>
I'm not sure how to build the XSD to support 1 required element without attributes, and 0-n elements with attributes given that they have the same name. With different names, it's a much easier matter, but that seems messy given that the elements are otherwise identical.
Edit:
To address @kjhughes's request, here's the simplified document structure:
<configuration>
<target>Production</target>
<responsible>[email protected]</responsible>
<server>
<cpu>65</cpu>
</server>
<server key="2">
<cpu>55</cpu>
</server>
</configuration>
Upvotes: 1
Views: 182
Reputation: 111726
You cannot have different elements of the same name within the same content model.
But you change the name of your second server
elements to reflect that they are server overrides:
<?xml version="1.0" encoding="UTF-8"?>
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="try.xsd">
<target>Production</target>
<responsible>[email protected]</responsible>
<server>
<cpu>65</cpu>
</server>
<server-override key="2">
<cpu>55</cpu>
</server-override>
</configuration>
And still share their commonality in the type definitions via extension:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="configuration">
<xs:complexType>
<xs:sequence>
<xs:element name="target"/>
<xs:element name="responsible"/>
<xs:element name="server" type="server-type"
minOccurs="1" />
<xs:element name="server-override" type="server-override-type"
minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="server-type">
<xs:sequence>
<xs:element name="cpu"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="server-override-type">
<xs:complexContent>
<xs:extension base="server-type">
<xs:attribute name="key" use="required"/>
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:schema>
Upvotes: 1
Reputation: 1605
Try JAXB unmarshalling, you create java objects that can be used to unmarshal the XML, this makes it easier to handle the XML Use the xsd for generationg the jaxb objects Depending on what IDE you have in eclipse you only need to right click your xmlroot and press generate jaxb,,,
Upvotes: 0