print webservice response line by line in console - java

I have below webservice response from outside vendor. Need to print each line in console. Below reponse is store in response object.
<?xml version="1.0" encoding="UTF-8"?>
<loginInformation xmlns="http://www.example.com/restapi" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<loginAccounts>
<loginAccount>
<accountId>117072</accountId>
<baseUrl>https://example.net/restapi/v2</baseUrl>
<email>abc#gmail.com</email>
</loginAccount>
</loginAccounts>
</loginInformation>
my output should be like below :
1.<?xml version="1.0" encoding="UTF-8"?>
2.<loginInformation xmlns="http://www.example.com/restapi" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
.
.
.
.

If you parse the XML string, serialize it and then get it back, you can do that in a few steps. Try this piece of code:
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
final class XmlFormatter {
private XmlFormatter() { }
private static Document parse(String in) {
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
final DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new InputSource(new StringReader(in)));
} catch (IOException | ParserConfigurationException | SAXException e) {
System.err.printf("Something happened here due to: %s", e);
}
return null;
}
public static String format(final String xml) {
final Document document = XmlFormatter.parse(xml);
final OutputFormat format = new OutputFormat(document);
final Writer out = new StringWriter();
final XMLSerializer serializer = new XMLSerializer(out, format);
format.setIndenting(true);
format.setLineWidth(120);
format.setIndent(2);
try {
serializer.serialize(document);
return out.toString();
} catch (IOException e) {
System.err.printf("Something happened here...this is why: %s", e);
}
return null;
}
public static void main(final String... args) {
System.out.printf("%s", XmlFormatter.format(/* YOUR UNFORMATTED XML */));
}
}

Related

HTMLEntities.res missing in my xerces.jar. Becuse of this i am facing compilation error

I am trying t o format xml content in xml document using org.apache.xml.serialize.OutputFormat,org.apache.xml.serialize.XMLSerializer. But I am getting compilation in my class that above file are can not be resovled .
Help me to resolve the issue..
import java.io.File;
import java.io.FileInputStream;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class XMLPrinter
{
public static String print(String input) throws Exception {
return print(input, null);
}
public static String print( String input , String aDocType) throws Exception
{
return print( input , aDocType, null);
}
public static String print( String input , String aDocType, String lineSeaparator) throws Exception
{
String output = "";
try
{
DocumentBuilderFactory docBuilderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder =
docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(
new InputSource( new StringReader(input)) );
StringWriter stringWriter = new StringWriter();
OutputFormat format = new OutputFormat( doc );
//NEW CODE
if(aDocType!=null)
format.setDoctype(null, aDocType);
format.setIndenting( true );
format.setLineWidth( 0 );
format.setIndent( 10 );
if(lineSeaparator != null)
format.setLineSeparator(lineSeaparator);
XMLSerializer serializer =
new XMLSerializer( stringWriter, format );
serializer.serialize(doc);
output = stringWriter.toString();
}
catch (Exception e)
{
e.printStackTrace();
//throw e;
//output = null;
throw e;
}
return output;
}
public static void main(String[] args) throws Exception
{
String XML ="";
File f = new File("E:\\interfaces\\ShipToPartyMaster100.xml");
FileInputStream fis = new FileInputStream(f);
byte[] buf = new byte[fis.available()];
fis.read(buf);
XML = new String(buf);
System.out.println(XMLPrinter.print(XML));
}
}
Where I am facing compilation in import of the above mentioned files.
Why this is happening ?? Does it becuse of missing HTMLEntities.res ??

Java XML update issue - appendchild() not sucessfully append element

I have an issue when I append a new node to xml dom. The following code is the dom saving code in xmlFactory.java.
import java.io.File;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import com.ism.msgmgt.domain.Post;
import com.ism.msgmgt.domain.User;
public class XmlFactory {
private static Document userdom;
private static Document postdom;
private static File userfile = new File(User.class.getResource("User.xml").getPath());
static {
try{
DocumentBuilderFactory dbuf = DocumentBuilderFactory.newInstance();
DocumentBuilder dbu = dbuf.newDocumentBuilder();
userdom = dbu.parse(userfile);
DocumentBuilderFactory dbpf = DocumentBuilderFactory.newInstance();
DocumentBuilder dbp = dbpf.newDocumentBuilder();
postdom = dbp.parse(postfile);
} catch (Exception e){
e.printStackTrace();
}
}
public static Document getUserDom(){
return userdom;
}
public static void saveUserDom(){
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
System.out.println(userdom.getFirstChild()+"|"+userdom.getFirstChild().getFirstChild());
DOMSource ds = new DOMSource(userdom);
StreamResult sr = new StreamResult(userfile);
trans.transform(ds, sr);
} catch (Exception e){
throw new RuntimeException(e.getMessage(),e);
}
}
}
Note that the printed output is [users: null]|[#text: ]. Next, it is the code in the UserDao.java.
public class UserDao {
public static Element currentUser = null;
public static Document userdom = XmlFactory.getUserDom();
public static void reg(User u){
clrLogin();
u.setUserid(UidUtil.getUid());
u.setPassword(PwdUtil.encode(u.getPassword()));
Element e = userdom.createElement("user");
e.setAttribute("id", u.getUserid());
e.setAttribute("username", u.getUsername());
e.setAttribute("password", u.getPassword());
e.setAttribute("login", u.getLogin());
userdom.getFirstChild().appendChild(e);
System.out.println(e);
System.out.println(userdom.getFirstChild()+"|"+userdom.getFirstChild().getFirstChild());
XmlFactory.saveUserDom();
currentUser = e;
}
}
Note that in this code, I printed the node I want to add, which is [user: null]. Next, I printed the expecting added node. However, I got the result [users: null]|[#text: ], which is the same as the output printed from above code. So it looks like appendChild() didn't add e to the dom's first node. Please help. Thanks.
XML File
<?xml version="1.0" encoding="UTF-8"?>
<users>
</users>
There's too much context missing from your question, for one, we don't know how the userdom is actually created...
Let me demonstrate, with the following code...
import java.io.ByteArrayOutputStream;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class Test1 {
public static Document userdom;
public static void main(String[] args) {
try {
userdom = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element root = userdom.createElement("users");
Node adoptNode = userdom.adoptNode(root);
userdom.appendChild(adoptNode);
reg();
} catch (ParserConfigurationException | DOMException exp) {
exp.printStackTrace();
}
}
public static void reg() {
Element e = userdom.createElement("user");
e.setAttribute("id", "blah");
e.setAttribute("username", "kermit");
e.setAttribute("password", "bunnies in the air");
e.setAttribute("login", "kermmi");
userdom.getFirstChild().appendChild(e);
System.out.println(e);
System.out.println(userdom.getFirstChild() + "|" + userdom.getFirstChild().getFirstChild());
saveUserDom();
}
public static void saveUserDom() {
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
System.out.println(userdom.getFirstChild() + "|" + userdom.getFirstChild().getFirstChild());
DOMSource ds = new DOMSource(userdom);
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
StreamResult sr = new StreamResult(baos);
trans.transform(ds, sr);
System.out.println(new String(baos.toByteArray()));
}
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}
I get the following output...
[user: null]
[users: null]|[user: null]
[users: null]|[user: null]
<?xml version="1.0" encoding="UTF-8" standalone="no"?><users><user id="blah" login="kermmi" password="bunnies in the air" username="kermit"/></users>
Which clearly demonstrates that the appendChild method is working fine.
An immediate concern is the relationship between...
public static Document userdom = XmlFactory.getUserDom();
and
DOMSource ds = new DOMSource(userdom);
One has to ask, are they the same reference (of userdom)?
Updated
This...
private static File userfile = new File(User.class.getResource("User.xml").getPath());
coupled with this...
StreamResult sr = new StreamResult(userfile);
Are your problems...
First, you are loading an internal resource and you should NEVER wrap these in File entry, internal/embedded resources are not accessible from a File context and need to be loaded in a different way, instead, maitain the URL refernce that getResource results...
private static URL userfile = User.class.getResource("User.xml");
The next line, (StreamResult sr = new StreamResult(userfile);) is trying to write the resulting DOM back to an embedded resource...embedded resources can not be written to in this fashion, hence the reason it would fail in a normal running environment (it might work in your IDE, but that's a different issue).
Basically, you can't maintain this information as an embedded resource, you need to externalise the file onto the disk.
FYI:
If you did use the URL of the resource properly, you would need to change the way you are loading the XML document to something like...
try (InputStream is = userfile.openStream()) {
userdom = dbu.parse(is);
}

JAVA XML PARSING TO SPLIT XML based on object and class tag elements

This is the JAVA XML i'm parsing..
<objects>
<object>...<class>A /<class>...</object>
<object>...<class>B</class>....</object>
<object>...<class>A /<class>...</object>
</objects>
Now i split the XML into 3 XML's based on object tag with the below code.
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse("xml");
doc.getDocumentElement().normalize();
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();
NodeList list =(NodeList) doc.getElementsByTagName("object");
System.out.println("XML SPLITED");
for (int i=0; i<list.getLength(); i++){
Node element = list.item(i).cloneNode(true);
if(element.hasChildNodes()){
Source src = new DOMSource(element);
FileOutputStream fs=new FileOutputStream("XML" + i + ".xml");
Result dest = new StreamResult(fs);
aTransformer.transform(src, dest);
fs.close();
}
My requirement is to get only the files with class tag A.So my output will be only 2 XML's.Please post your answers.
Using your example, you can do that this way:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XmlSplitting {
private static final Logger logger = Logger.getLogger(XmlSplitting.class.getName());
private static final String FILE_PATH = "./";
private DocumentBuilder builder;
private Transformer transformer;
public XmlSplitting() throws ParserConfigurationException, TransformerConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
this.builder = factory.newDocumentBuilder();
TransformerFactory transfromerFactory = TransformerFactory.newInstance();
this.transformer = transfromerFactory.newTransformer();
}
public static void main(String[] args) {
try {
XmlSplitting s = new XmlSplitting();
s.run();
} catch (ParserConfigurationException | SAXException | IOException | TransformerException x) {
logger.log(Level.SEVERE, "Error", x);
}
}
private void run() throws ParserConfigurationException, SAXException, IOException, TransformerException {
File file = new File(FILE_PATH + "xml.xml");
if (file.exists()) {
Document document = this.builder.parse(file);
document.normalize();
NodeList list = document.getElementsByTagName("object");
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
if (Node.ELEMENT_NODE == node.getNodeType()) {
Element object = (Element)node;
NodeList classes = object.getElementsByTagName("class");
if (1 == classes.getLength()) {
Node clazz = classes.item(0);
if (Node.ELEMENT_NODE == clazz.getNodeType()) {
this.copyNodeToNewFile(clazz.getTextContent(), node, i);
}
} else {
logger.log(Level.SEVERE, "Number of class nodes in node object is different than expected. Number of class nodes found: {0}.", classes.getLength());
}
}
}
} else {
logger.log(Level.SEVERE, "You provided wrong path for xml file.");
}
}
private void copyNodeToNewFile(String content, Node node, int i) throws IOException, TransformerException {
boolean copy = this.nodeShouldBeCopied(content);
logger.log(Level.INFO, "Node with content {0} will {1}be moved to separete file.", new Object[]{content, true == copy ? "" : "not "});
if (copy) {
String fileName = String.format("%sxml%d.xml", FILE_PATH, i);
try (FileOutputStream fos = new FileOutputStream(fileName)) {
Source source = new DOMSource(node);
Result destination = new StreamResult(fos);
this.transformer.transform(source, destination);
}
}
}
// here you can change condition to copy given node to file
private boolean nodeShouldBeCopied(String content) {
return content.contains("A");
}
}
How about using a Brazilian framework to parse your XML? it will make your code more exotic and you can tell your friends about it:
http://jcoltrane.sourceforge.net/userguide/extending_parsing_process.html

Regarding XPath using Java

I have a problem in getting the value of an element by providing the XPath using java. I tried lot of things but could not succeed.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.dell.logistics.framework.transform.NamespaceContext;
public class GetXPath {
protected Object evaluate(String xpathStr, String xml, String namespaces) throws XPathExpressionException {
InputSource inputSource = new InputSource(new StringReader(xml));
XPathFactory factory = XPathFactory.newInstance();
XPath xPath = factory.newXPath();
NamespaceContext nsContext = new NamespaceContext();
nsContext.setNamespacesMap(getNsMap(namespaces));
//System.out.println(nsContext.getPrefix(namespaces));
xPath.setNamespaceContext(nsContext);
XPathExpression xpExp = xPath.compile(xpathStr);
return xpExp.evaluate(inputSource, XPathConstants.NODESET);
}
private Map<String, String> getNsMap(String namespaces) {
String delims = ",";
String[] nsKeyValue = namespaces.split(delims);
Map<String, String> mp = new HashMap<String, String>();
for (String string : nsKeyValue) {
mp.put(string.split("=")[0], string.split("=")[1]);
System.out.println(string.split("=")[0] + string.split("=")[1]);
}
return mp;
}
public static String readFile(String fileName) {
try {
// InputStream is = null;
InputStream is = GetWorkOrderDataExtractor.class.getResourceAsStream(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
String l = null;
while ((l = br.readLine()) != null) {
sb.append(l).append("\n");
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args)
throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException {
GetXPath g = new GetXPath();
String xml = readFile("fooewo.xml");
String value = null;
System.out.println(xml);
NodeList containerNodes = (NodeList) g.evaluate(
"/demo",xml,
"a=http://schemas.demo.com/it/WorkOrderChannelAckNackResponse/1.0");
try{
for (int i = 0; i < containerNodes.getLength(); i++) {
// get the node value.
value = containerNodes.item(i).getTextContent();
System.out.println(value);
}
System.out.println("Node Found : " + containerNodes.getLength() + " times");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
"
XML file:
<?xml version="1.0" encoding="utf-8"?>
<demo xmlns="try with ur schema">
<test>
<value>10</value>
<color>red</color>
<animal>dog</animal>
<day>13</day>
<age>22</age>
</test>
<test>
<value>20</value>
<color>green</color>
<animal>cat</animal>
<day>12</day>
<age>23</age>
</test>
</demo>
Any help appreciated.
Thanks,
Pradeep
I think the best way to evaluate XPath easily is using AXIOMXPath
Here is an example,
OMElement documentElement = new StAXOMBuilder(inStreamToXML).getDocumentElement();
AXIOMXPath xpathExpression = new AXIOMXPath ("/demo");
List nodeList = (OMNode)xpathExpression.selectNodes(documentElement);
By traversing the list you can get the result easily.

How to get error's line number while validating a XML file against a XML schema

I'm trying to validade a XML against a W3C XML Schema.
The following code does the job and reports when error occurs. But I'm unable to get line number of the error. It always returns -1.
Is there a easy way to get the line number?
import java.io.File;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.w3c.dom.Document;
import org.xml.sax.SAXParseException;
public class XMLValidation {
public static void main(String[] args) {
try {
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(new File("myxml.xml"));
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source schemaFile = new StreamSource(new File("myschema.xsd"));
Schema schema = factory.newSchema(schemaFile);
Validator validator = schema.newValidator();
validator.validate(new DOMSource(document));
} catch (SAXParseException e) {
System.out.println(e.getLineNumber());
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I found this
http://www.herongyang.com/XML-Schema/Xerces2-XSD-Validation-with-XMLReader.html
that appears to provide the following details(to include line numbers)
Error:
Public ID: null
System ID: file:///D:/herong/dictionary_invalid_xsd.xml
Line number: 7
Column number: 22
Message: cvc-datatype-valid.1.2.1: 'yes' is not a valid 'boolean'
value.
using this code:
/**
* XMLReaderValidator.java
* Copyright (c) 2002 by Dr. Herong Yang. All rights reserved.
*/
import java.io.IOException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
class XMLReaderValidator {
public static void main(String[] args) {
String parserClass = "org.apache.xerces.parsers.SAXParser";
String validationFeature
= "http://xml.org/sax/features/validation";
String schemaFeature
= "http://apache.org/xml/features/validation/schema";
try {
String x = args[0];
XMLReader r = XMLReaderFactory.createXMLReader(parserClass);
r.setFeature(validationFeature,true);
r.setFeature(schemaFeature,true);
r.setErrorHandler(new MyErrorHandler());
r.parse(x);
} catch (SAXException e) {
System.out.println(e.toString());
} catch (IOException e) {
System.out.println(e.toString());
}
}
private static class MyErrorHandler extends DefaultHandler {
public void warning(SAXParseException e) throws SAXException {
System.out.println("Warning: ");
printInfo(e);
}
public void error(SAXParseException e) throws SAXException {
System.out.println("Error: ");
printInfo(e);
}
public void fatalError(SAXParseException e) throws SAXException {
System.out.println("Fattal error: ");
printInfo(e);
}
private void printInfo(SAXParseException e) {
System.out.println(" Public ID: "+e.getPublicId());
System.out.println(" System ID: "+e.getSystemId());
System.out.println(" Line number: "+e.getLineNumber());
System.out.println(" Column number: "+e.getColumnNumber());
System.out.println(" Message: "+e.getMessage());
}
}
}
Replace this line:
validator.validate(new DOMSource(document));
by
validator.validate(new StreamSource(new File("myxml.xml")));
will let the SAXParseException contain line number & column number
Try using a SAXLocator
http://download.oracle.com/javase/1.5.0/docs/api/org/xml/sax/Locator.html
Parsers are not required to supply one, but if they do it should report line numbers
I think your code should include:
// this will be called when XML-parser starts reading
// XML-data; here we save reference to current position in XML:
public void setDocumentLocator(Locator locator) {
this.locator = locator;
}
(see http://www.java-tips.org/java-se-tips/org.xml.sax/using-xml-locator-to-indicate-current-parser-pos.html)
The parser will give you a locator which you can then use to get the line number. It's probably worth printing/debugging when this happens to see if you have a valid locator
Assuming the final objective is to have a validated DOM instance, the previous answers would require XML documents to be read twice — first for validation, and then again to build the object tree. That's fine if the document is given as a file path, but it would require some sort of workaround if it were provided as an input stream, which in principle can only be read once.
A more efficient alternative is to use a validating parser to check the XML document against the schema as the object tree is built. See the code below for how to setup a schema-validating DOM parser:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.w3c.dom.Document;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class XML {
public static Document load(String xml, String xsd) {
// The default error handler just prints errors to the standard error output. In
// order to make the parser interrupt its work once a validation error is found,
// we need to use a custom handler that throws an exception in response to any
// reported issues.
ErrorHandler errorHandler = new ErrorHandler() {
#Override
public void error(SAXParseException exception) throws SAXException {
throw exception;
}
#Override
public void fatalError(SAXParseException exception) throws SAXException {
throw exception;
}
#Override
public void warning(SAXParseException exception) throws SAXException {
throw exception;
}
};
try {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new File(xsd));
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
builderFactory.setSchema(schema);
DocumentBuilder builder = builderFactory.newDocumentBuilder();
builder.setErrorHandler(errorHandler);
InputStream input = new FileInputStream(xml);
Document document = builder.parse(input);
return document;
}
catch (SAXParseException e) {
int row = e.getLineNumber();
int col = e.getColumnNumber();
String message = e.getMessage();
System.out.println("Validation error at line " + row + ", column " + col + ": \"" + message + '"');
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String xml = args[0];
String xsd = args[1];
Document document = load(xml, xsd);
boolean valid = (document != null);
System.out.println("Document \"" + xml + "\" is " + (valid ? "" : "not ") + "valid against schema \"" + xsd + '"');
}
}

Categories