DocumentBuilder - setNamespaceAware - setNamespaceAware cannot resolve method - java

i'm tryng to set NamespaceAware(true) using the setNamespaceAware method of javax.xml.parsers.DocumentBuilder, but i find the following error:
Error:(31, 16) java: cannot find symbol
symbol: method setNamespaceAware(boolean)
location: variable builder of type javax.xml.parsers.DocumentBuilder
Code:
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
builder.setNamespaceAware(true);
(of course i added: import javax.xml.parsers.DocumentBuilderFactory and import org.w3c.dom.Document;)
Thanks

Related

How to ignore Fatal Errors using java Sax Parer

I am parsing html using java sax parser, its mostly well formatted but not all tags are terminated,
unfortunately I cannot change the source.
Is it possible to tell the java Sax Parser to ignore Fatal Errors ?
Errors like:
SAXParseException;
The entity "nbsp" was referenced, but not declared.
The element type "img" must be terminated by the matching end-tag "</img>".
The element type "meta" must be terminated by the matching end-tag "</meta>".
This is the code I am using:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringComments(true);
//factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false);
// factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
Document doc = builder.parse(is);

newInstance() is not displayed for XML file creation in java

I had imported javax.xml.parsers.DocumentBuilder, javax.xml.parsers.DocumentBuilderFactory for XML manipulation. While creating reference for document builderfactory, the newinstance() was not displayed. Anyone help me to fix it?
Syntax:
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();

Error loading XML schema with Java

I'm trying to parse an using this schema, but I get the following error:
org.xml.sax.SAXParseException; systemId: http://www.khronos.org/files/collada_schema_1_4.xsd; lineNumber: 1; columnNumber: 50; White spaces are required between publicId and systemId.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:177)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:441)
...
Here's the relevant section of my code:
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setValidating(true);
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
URL schemaURL = new URL("http://www.khronos.org/files/collada_schema_1_4.xsd");
Schema schema = sf.newSchema(schemaURL); //Line causing error
dbFactory.setSchema(schema);
DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
Document doc = docBuilder.parse(file);
doc.getDocumentElement().normalize();
This question says that there should be spaces between all of the xsi:schemaLocations, but there are already spaces between them. Some of the comments hint that it may be an issue with Eclipse, which is definitely a possibility.
This question says that it's a problem with the doctype declaration, but I don't know where a the comparable section of code is in my document.
The error message comes when you seek to make a new schema object from the document whose URI is http://www.khronos.org/files/collada_schema_1_4.xsd.
There seems to be a good chance that the data the error message is complaining about is the data retrieved from that URI. Have you tried dereferencing the URI? What did you get?
What I got is a 404 accompanied by an HTML error page which begins:
<!DOCTYPE html>
This is not a legal XML document type declaration, and thus cannot possibly be the beginning of a legal XSD schema document. The error message isn't providing a very good diagnosis of the problem (it suggests that the input does have a public identifier and a system identifier, but they lack a separating whitespace, when the basic problem is that neither is present at all), but the fix is unrelated to the details of the error message. The fix is to find the correct URI for the schema document you want to load: http://www.khronos.org/files/collada_schema_1_4 not http://www.khronos.org/files/collada_schema_1_4.xsd.

creat simple xml

I am trying to build server that sends a xml file to client. I am getting info from db and wants to build from that xml file.
But I have a problem with :
DocumentBuilder documentBuilder = null;
Document doc =documentBuilder.newDocument();
I am getting NullPointerException. Here is me full code:
public void createXmlTree() throws Exception {
//This method creates an element node
DocumentBuilder documentBuilder = null;
Document doc =documentBuilder.newDocument();
Element root = doc.createElement("items");
//adding a node after the last child node of the specified node.
doc.appendChild(root);
for(int i=0;i<db.stories.size();i++){
Element child = doc.createElement("item");
root.appendChild(child);
Element child1 = doc.createElement("title");
child.appendChild(child1);
Text text = doc.createTextNode(db.stories.get(i).title);
child1.appendChild(text);
//Comment comment = doc.createComment("Employee in roseindia");
//child.appendChild(comment);
Element child2 = doc.createElement("date");
child.appendChild(child2);
Text text2 = doc.createTextNode(db.stories.get(i).date);
child2.appendChild(text2);
Element child3 = doc.createElement("text");
child.appendChild(child3);
Text text3 = doc.createTextNode(db.stories.get(i).text);
child3.appendChild(text3);
root.appendChild(child3);
Well yes, you would get a NullPointerException. You're calling a method on a null reference - very clearly, given that you've assigned the documentBuilder a null value on the line before. You need to get an instance of DocumentBuilder to start with. For example:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
of course you are getting a NullPointerException, your DocumentBuilder is null.
Try instantiating it first.
// Step 1: create a DocumentBuilderFactory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// Step 2: create a DocumentBuilder
DocumentBuilder db = dbf.newDocumentBuilder();
Guys are right about DocumentBuilder. But may I offer you other solution? Your servlet mostly deals with generating of XML itself, i.e. produces kind of markup. This is the purpose of JSP. You can implement simple JSP page that will actually contain template of your XML and some code that inserts dynamic data. This is much simpler and easier to maintain.
Yes, JSP typically generate HTML but no-one said that they cannot generate XML or any other text format. Just do not forget to set content type to text/xml.
Do you really need to write you XML manually?
Do you have the XSD of the XML you want to write?
Because, it would be easier to generate some classes using XJC/JAXB and use the marshaller to write your XML file.

org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'tns:root_element'

I have spent past 2 hours on this. Am unable to figure out why this error is occurring. I have a simple xsd and xml code
xml file:
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema">
<element name="root_element" type="string"/>
</schema>
xsd file:
<?xml version="1.0" encoding="UTF-8"?>
<root_element>"asd"</root_element>
My java code is:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
SchemaFactory s_factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
dbf.setSchema(s_factory.newSchema(new File(schemafile)));
dbf.setValidating(true);
dbf.setFeature("http://apache.org/xml/features/validation/schema", true);
DocumentBuilder db = dbf.newDocumentBuilder();
CommodityPropsErrorHandler cp_eh = new CommodityPropsErrorHandler();
db.setErrorHandler(cp_eh);
Document doc = db.parse(new File(props_file));
Any comments would be helpful. regards
I think that main issue is with:
dbf.setValidating(true);
According to Java API, DocumentBuilderFactory.setValidating:
Specifies that the parser produced by this code will validate
documents as they are parsed. By default the value of this is set to
false.
Note that "the validation" here means a validating parser as defined
in the XML recommendation. In other words, it essentially just
controls the DTD validation. (except the legacy two properties
defined in JAXP 1.2.)
To use modern schema languages such as W3C XML Schema or RELAX NG
instead of DTD, you can configure your parser to be a non-validating
parser by leaving the setValidating(boolean) method false, then
use the setSchema(Schema) method to associate a schema to a parser.
Also you don't need:
dbf.setFeature("http://apache.org/xml/features/validation/schema", true);
Your working code probably is just (however I don't know what is in CommodityPropsErrorHandler class):
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
SchemaFactory s_factory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
dbf.setSchema(s_factory.newSchema(new File(schemafile)));
DocumentBuilder db = dbf.newDocumentBuilder();
CommodityPropsErrorHandler cp_eh = new CommodityPropsErrorHandler();
db.setErrorHandler(cp_eh);
Document doc = db.parse(new File(props_file));
Here is second, alternative approach with previous dbf.setValidating(true); (that is, using this two properties from JAXP, mentioned in Java API):
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(true);
dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
XMLConstants.W3C_XML_SCHEMA_NS_URI);
dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource",
new File(schemafile));
DocumentBuilder db = dbf.newDocumentBuilder();
CommodityPropsErrorHandler cp_eh = new CommodityPropsErrorHandler();
db.setErrorHandler(cp_eh);
Document doc = db.parse(new File(props_file));
This line is for making validation namespace aware. Otherwise it will give Element not present in the doc.
dbf.setNamespaceAware(true);

Resources