Error writing XML Document to file in Java - java

I am trying to write org.w3c.dom.Document to a file. I get the Document from
String URL = "http://...."
DOMParser parser = new DOMParser();
Document doc = null;
try {
parser.parse(new InputSource(URL));
doc = parser.getDocument();
} catch () {}
Then I write this Document to a file using
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(file));
transformer.transform(source, result);
While doing this I keep getting the following error
ERROR: 'Namespace for prefix 'xlink' has not been declared.'
What might be wrong? Thanks

I recommend using a different library such as Dom4J rather than trying to fight your way through the built-in XML API in Java. Dom4J is better designed and makes your code much more readable:
Document doc = new SAXReader().read(inputStream);
new XMLWriter(outputStream).write(doc);
None of this mucking around with FactoryFactoryFactoryFactories.
I know this doesn't directly answer your question but hopefully it will help anyway. Dom4j knows how to talk to the Java XML API so you can mix and match them to suit your needs. You can even plug it into Xalan or something similar if you want to use XSLT.

Related

How to save escaped symbols " after parsing and saving xml file via java dom

For example I have an input.xml file with next content:
<root>"Hello World!"</root>
Then I read it and parse:
// parse xml file
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("input.xml"));
doc.getDocumentElement().normalize();
Suppose i just want to save it in other place:
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Result output = new StreamResult(new FileOutputStream("output.xml"));
doc.setXmlStandalone(true);
Source input = new DOMSource(doc);
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.transform(input, output);
And I get output.xml file :
<root>"Hello World!"</root>
What i need to do to avoid this replacement?
I have not found any solution anywhere.
This question is similar to Is there a Java XML API that can parse a document without resolving character entities? and Java XML Parsing: Avoid entity reference resolution
If you want to keep entity reference, you need a special XML parser.

Java XML dom: prevent collapsing empty element

I use the javax.xml.parsers.DocumentBuilder, and want to write a org.w3c.dom.Document to a file.
If there is an empty element, the default output is a collapsed:
<element/>
Can I change this behavior so that is doesn't collapse the element? I.e.:
<element></element>
Thanks for your help.
This actualy depends on the way how you're writing a document to a file and has nothing to do with DOM itself. The following example uses popular Transformer-based approach:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document document = factory.newDocumentBuilder().newDocument();
Element element = document.createElement("tag");
document.appendChild(element);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "html");
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
It outputs <tag></tag> as you're expecting. Please note, that changing the output method has other side effects, like missing XML declaration.

Java XML Transformer : Empty elements in long notation instead of short

I have created a conversion tool to add some information to an existing xml file.
This is done by using DOM and the Transformer class.
The output file will be processed by third party software.
This TPS needs the empty tags from the input and outputfile in Long Notation.
Unfortunately, transformer class always change them to short notation.
Is there a way to prevent this from happenning?
I have been searching various sites, but haven't found a solution that really fits my needs.
Please help,
Thanks,
Kind regards,
Maarten
You can transform the DOM to StAXResult.
For instance,
XMLOutputFactory factory=XMLOutputFactory.newFactory();
XMLStreamWriter writer=factory.createXMLStreamWriter(System.out);
StAXResult result=new StAXResult(writer);
trans.transform(new DOMSource(doc),result);
XMLOutputFactory factory = XMLOutputFactory.newFactory();
XMLStreamWriter writer = factory.createXMLStreamWriter(System.out);
StAXResult result = new StAXResult(writer);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(new DOMSource(doc), result);

Transformer's transform causes a fatal error, why?

I've built a document using JAXP like this:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Element rootElement = document.createElement("Root");
for (MyObject o : myCollection) {
Element entry = document.createElement("Entry");
Element entryItem = document.createElement("EntryItem");
entryItem.appendChild(document.createTextNode(o.getProperty()));
entry.appendChild(entryItem);
rootElement.appendChild(entry);
}
document.appendChild(rootElement);
Now, when I try to output the XML for the document like this:
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new StringWriter());
transformer.transform(source, result);
System.out.println(result.getWriter().toString());
It falls apart on the transformer.transform line with the following error:
FATAL ERROR: 'java.lang.NullPointerException'
:null
How do I go about debugging this? I've made sure that transformer, source and result aren't null.
I'm guessing that this:
entryItem.appendChild(document.createTextNode(o.getProperty()));
created a text node with a null value. Looking at Xerces' code (which is the default JAXP implementation shipped with Oracle's JDK 1.6), I see no null validation done at the time of constructing the text node. I suspect that that, later, makes the Transformer die.
Either that, or there's some JAXp configuration problem.
You may wish to set the jaxp.debug system property (available JDK 1.6+) to get some JAXP tracing information.
--How about the document?
Ooops sorry, obviously the second part follows the first :) Which parser are you using?

How to get a non-XML output using JDOM XSLTransformer?

I have an XML file which I'd like to parse into a non-XML (text) file based on a XLST file. The code in both seem correct, and it works when testing manually, but I'm having a problem doing this programatically.
I'm using JDOM's XSLTransformer class to apply the XSLT to the XML and it returns it in the format of a JDOM Document. The problem here is that I can't seem to access anything in the Document as it is not a proper XML file and I get a "java.lang.IllegalStateException: Root element not set" error.
Is there a better way within Java to obtain a non-XML file as a result of XSLT?
JDOM XSLTTransformer is a convenience wrapper around javax.xml.transform.Transformer for JDOM input and output.
A JDOM input is easily transformed to text output.
Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(stylesheet));
JDOMSource in = new JDOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult out = new StreamResult(writer);
transformer.transform(in, out);
return writer.toString();

Categories