dom4j - xpath - get xml as string for Document.valueOf - java

Is there a way to write XPath expression that will be returning xml tree as string when called with Document.valueOf method from dom4j library? I tried /node(), but it returns just texts in all nodes, not including tags.

Method 1 :
String result = document.toXML().toString();
Method 2 : (a more elegant aproach)
DOMSource domSource = new DOMSource(document);
StringWriter writer = new StringWriter();
StreamResult streamResult = new StreamResult(writer);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory .newTransformer();
transformer.transform(domSource, streamResult);
String result = writer.toString();

Related

How to print xml file colored in console using java

I'm trying to print an XML file colored on console using java, but I have never done this before, and I have no idea how to do that.
This code prints an XML file on console.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder1;
builder1 = factory.newDocumentBuilder();
Document document;
document = builder1.parse(new File(pathFilename));
TransformerFactory tFactory = TransformerFactory.newInstance();
tFactory.setAttribute("indent-number", new Integer(2));
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(document);
StreamResult result2 = new StreamResult(System.out);
transformer.transform(source, result2);
I would like to print it on console like an editor, for example Notepad++.
Any suggests how to do it?
An example of output on console:
<ControllerMode dataItemId="mode" sequence="286201" timestamp="2019-06-27T11:23:02.641182Z">AUTOMATIC</ControllerMode>

Store xml into xml attribute

How can I store a xml document into xml attribute? I have this code but de output give me escape characters, is right left with these escape characters?
public static void main(String[] args) throws TransformerException,
ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element organizations = doc.createElement("ORGANIZATIONS");
doc.appendChild(organizations);
organizations.setAttribute("xml", "<root><first>01</first><second>02</second></root>");
DOMSource domSource = new DOMSource(doc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
StreamResult sr = new StreamResult(new File("test.xml"));
transformer.transform(domSource, sr);
}
output:
<ORGANIZATIONS xml="<root><first>01</first><second>02</second></root>"/>
This is correct. The xml should be escaped when set on an attribute.
If you want to see the plain xml, you have to put it on an element and force the usage of CDATA sections for it:
transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "thequalifiednameoftheelement");
CDATA sections cannot be used on attributes... Attributes are not made for being filled with xml documents...

XML file saved from Swing application

I'm developing a Java Swing Application, and I want to create objects and save them in a XML file, with the information that a user writes in some text fields.
How can I save that data into a XML file, to form those objects?
You can write your own XML-Writer to write out objects/text to a XML file. For example using DOM
public boolean writeCommonSettingsFromGUI()
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("NAME_OF_A_ELEMENT");
doc.appendChild(rootElement);
Element xmlInfo = doc.createElement("NAME_OF_ANOTHER_ELEMENT");
xmlInfo.setTextContent("YOUR_CONTENT_TO_SET_FOR_THIS_ELEMENT");
rootElement.appendChild(xmlInfo);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "5");
transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
DOMSource source = new DOMSource(doc);
StreamResult result = null;
result = new StreamResult(new File("FILE_PATH_WHERE_TO_SAVE_YOUR_XML"));
transformer.transform(source, result);
return true;
}
use castor framework, you can map your java class to xml file and vice versa

We are upgrading our application to java6 and an xsl transform that worked with java 5 now returns an empty document

Has anybody seen anything like this before? I will post the xsl and xml if I have to but I would have to take sensitive data out of it.
The code used to handle the XSL transformation:
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(new DOMSource( xslDoc));
DOMResult domresult = new DOMResult();
transformer.transform(new DOMSource(xmlDoc), domresult);
Node node = domresult.getNode();
resultDoc = (Document) node;
Never seen it going blank. For JAVA6 (also compatible with 1.5), I have the following code that is working, the difference seems to on TransformerFactory used.
private DocumentBuilderFactory factory;
private DocumentBuilder builder;
private Transformer xformer;
//presetup - needs to be done just once
factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
builder = factory.newDocumentBuilder();
xformer = TransformerFactory.newInstance().newTransformer();
//Transform the file
Source source = new DOMSource(doc);
String oFileName = "output.xml";
File oFile = new File(outputDirectory + "/" + oFileName);
Result result = new StreamResult(oFile);
xformer.transform(source, result);
Does this correct your issue?

Java: Saving StreamResult to a file

I am doing some data conversion(like csv) to xml with SAX then using transformer in Java. The result is in StreamResult, and I am trying to save this result to a file.xml but I can't find way to save StreamResult into file. am I doing this all wrong?
Your StreamResult should be created on the basis of a file, e.g.
StreamResult sr = new StreamResult(new File("/my/file.xml"));
If you give your Transformer such a StreamResult, it will write its result directly into the file you specified.
I am not familiar with the API... but does this link give you what you are after?
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);

Categories

Resources