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开发者_如何学C 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>
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.
I would suggest you to use JAXB for that. Search the Internet for tutorials.
Steps to proceed further with JAXB,
- Generate Java files using JAXB by providing the schema
- Unmarshal your XML to generated Java classes (beans). Don't do validation or set validation handler here.
- 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)
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
Use a DOM parser.Has methods to traverse XML trees, access, insert, and delete nodes
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.
精彩评论