Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts

XML to JAVA with @XmlType instead of @XmlRootElement

Posted on by Kim

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

...

private AssessResponse loadOpaResponseFromXmlFile(String file) throws Exception {
    JAXBContext jaxbContext = JAXBContext.newInstance(AssessResponse.class);
    InputStream is = getClass().getResourceAsStream(file);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    return unmarshaller.unmarshal(new StreamSource(is), AssessResponse.class).getValue();
}

----------------------

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AssessResponse", propOrder = {
    "versionInfo",
    "events",
    "globalInstance"})
public class AssessResponse
    implements Serializable
{

...

----------------------
<assess-response xmlns="http://oracle.com/determinations/server/12.2.1/rulebase/assess/types">
    <global-instance>
        <entity id="month" inferred="false">
            <instance id="xxx">

...

Method to preetyPrint Document in java

Posted on by Kim

public static void write(org.dom4j.Document document) {
        try {
            // Pretty print the document to System.out
            org.dom4j.io.OutputFormat format = org.dom4j.io.OutputFormat.createPrettyPrint();
            org.dom4j.io.XMLWriter writer = new org.dom4j.io.XMLWriter(new FileWriter("C:\\output.xml"), format);
            writer.write(document);
            writer.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

Nice framework for testing (equals) xml: XmlUnit

XSL Warning in Eclipse

Posted on by Kim

To make folling error

No grammar constraints (DTD or XML schema) detected for the document.

go away, add folling:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xsl:stylesheet [<!ENTITY bullet "•"> <!ENTITY nbsp " ">]>

Change • to & #x2022;
and space to & #xa0; with no space between & and #

Parese XML without DTD validation

Posted on by Kim

Use the Saxparser...

import org.w3c.dom.Document;

JDom

private static Document getDocumentFromInputStreamTest(InputStream is, boolean validate) throws JDOMException, IOException {
SAXBuilder parser = new SAXBuilder();
parser.setEntityResolver(new EntityResolver() {
public InputSource resolveEntity(String publicId, String systemId) {
if (!validateUrl(systemId))
return new InputSource(new ByteArrayInputStream("".getBytes()));
else
return null;
}
});

return new org.jdom.output.DOMOutputter().output(parser.build(is));
}

public static final boolean validateUrl(String aURL) {
try {
java.net.URL url = new URL(aURL);
if ("file".equals(url.getProtocol())) {
File f = new File(url.getFile());
if (f.isFile() && f.canRead())
return true;
} else if ("http".equals(url.getProtocol())) {
URL u = new URL(aURL);
u.openStream();
return true;
}
} catch (Exception e) {
}
return false;
}