Nawa
Nawa

Reputation: 2158

How to detect required XML attributes?

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

Answers (4)

Adeel Ansari
Adeel Ansari

Reputation: 39907

I would suggest you to use JAXB for that. Search the Internet for tutorials.

Steps to proceed further with JAXB,

  1. Generate Java files using JAXB by providing the schema
  2. Unmarshal your XML to generated Java classes (beans). Don't do validation or set validation handler here.
  3. Populate those classes with appropriate values. 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)
  4. 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

Shilaghae
Shilaghae

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

Andreas Krueger
Andreas Krueger

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

Cris
Cris

Reputation: 5007

Use a DOM parser.Has methods to traverse XML trees, access, insert, and delete nodes

Upvotes: 0

Related Questions