Reputation: 2158
I have an XML content without defined attributes, like this:
<rootElement>
<subElement1/>
</rootElement>
I want to populate this XML content with required attributes defined in XML Schema (XSD) for this XML.
For example, according to XSD subElement1 has required attribute 'id'.
What is the best way (for Java processing) to detect that and add such attributes to XML? We need to add required attributes and set appropriate values for them.
As a result for example above we need to have the following XML:
<rootElement>
<subElement1 id="some-value"/>
</rootElement>
Upvotes: 0
Views: 3218
Reputation: 39907
I would suggest you to use JAXB for that. Search the Internet for tutorials.
Steps to proceed further with JAXB,
required
elements can be found using annotation look up. JAXB annotation for element would look like something, @XmlElement(name = "ElementName", required = true)
. And an attribute annotation would be something similar to this, @XmlAttribute(required = true)
Marshal your bean back to XML. You can validate your bean using ValidationHandler
, while marshalling. Below is the sample code snippet,
marshller = JAXBContext.newInstance(pkgOrClassName).createUnmarshaller();
marshller.setSchema(getSchema(xsd)); // skip this line for unmarshaller
marshller.setEventHandler(new ValidationHandler()); // skip this line for unmarshaller
Upvotes: 3
Reputation: 957
I have had the same idea of Cris but I think that with this validator you don't have information about the point in which you have had the error. I think that you have to create or extend your own validator.
Upvotes: 0
Reputation: 1507
In the XML schema definition, i.e. XSD file, attributes are optional by default. To make an attribute required, you have to define:
<xs:attribute name="surname" type="xs:string" use="required"/>
You will find a very good introduction on XML and XML Schema Definitions, i.e. XSD, on W3 Schools.
In Java the equivalent of defining a XML schema is using JAXB, i.e. Java API for XML Binding that is included into Java SE. There you would define, e.g.
@XmlRootElement
public class Person { public @XmlAttribute(required=true) String surname; }
Hope this could clarify your question.
Upvotes: 3
Reputation: 5007
Use a DOM parser.Has methods to traverse XML trees, access, insert, and delete nodes
Upvotes: 0