I added the solution to the code below.
The code at the bottom is what I have. I removed the creation of all tags.
At the top in the xml file I get.<?xml version="1.0" encoding="UTF-8" standalone="no"?> Note that standalone is no, even thou I have it set to yes.
The first question: How do I get standalone = yes?
I would like to add <?xml-stylesheet type="text/xsl" href="my.stylesheet.xsl"?> at line two in the xml file.
Second question: How do I do that?
Some useful links? Anything?
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.newDocument();
doc.setXmlStandalone(true);
ProcessingInstruction pi = doc.createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"my.stylesheet.xsl\"");
Element root = doc.createElement("root-element");
doc.appendChild(root);
doc.insertBefore(pi, root);
<cut>
TransformerFactory transfac = TransformerFactory.newInstance();
transfac.setAttribute("indent-number", new Integer(2));
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
trans.setOutputProperty(OutputKeys.STANDALONE, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "name");
FileOutputStream fout = new FileOutputStream(filepath);
BufferedOutputStream bout= new BufferedOutputStream(fout);
trans.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(bout, "utf-8")));
I added
doc.setXmlStandalone(true);
ProcessingInstruction pi = doc.createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"my.stylesheet.xsl\"");`
before the cut and
doc.insertBefore(pi, root);
right after the root element was appended to the doc.
in my code, I wrote :
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
document.setXmlStandalone(true);
TransformerFactory tfactory = TransformerFactory.newInstance();
Transformer transformer = tfactory.newTransformer();
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
output:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
Related
I want to create an xml file with line breaks, looking somewhat like this:
<Instrument currencyId="THB"
disabledCount="0"
hasBeenEnabledOnce="TRUE"
</Instrument>
Using this code I got close but all attributes seems to be end up on the same row:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("Instrument");
doc.appendChild(rootElement);
Instrument.setAttribute("currencyId", "THB");
Instrument.setAttribute("disabledCount", "0");
Instrument.setAttribute("hasBeenEnabledOnce", "TRUE");
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:\\file.xml"));
transformer.transform(source, result);
I get the following result:
<Instrument currencyId="THB" disabledCount="0" hasBeenEnabledOnce="TRUE"
How can I add linebreaks between the attributes??
just a slight notice, I thought that transformer.setOutputProperies could solve the problem, by searching for similar problems I ended up with "OutputKeys.INDENT", "yes", and the indent-amount -> "4". But nothing's changed.
Doesnt matter if I open the file in notepad++ or as a webpage.
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
I've a xml document, which will be used as a template
<?xml version="1.0" encoding="UTF-8" standalone="no"?><entry xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"><content type="application/xml"><m:properties><d:AccountEnabled>true</d:AccountEnabled><d:DisplayName>SampleAppTestj5</d:DisplayName><d:MailNickname>saTestj5</d:MailNickname><d:Password>Qwerty1234</d:Password><d:UserPrincipalName>saTestj5#identropy.us</d:UserPrincipalName></m:properties></content></entry>
I'm calling it in java using this code where payLoadXML.xml has the above content.
"InputStream is = getClass().getClassLoader().getResourceAsStream("/payLoadXML.xml");"
Now I'm trying to edit the tag values for example changing the from "saTestj5" to "saTestj6" and then converting this entire xml and storing it in xml. Can anyone tell me how can I achieve this? I was told this can be done by using "Node" is it possible?
Use jaxb or sax parsers convert into object by using getter method and change the object and convert back to xml
try this
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = null;
docBuilder = docFactory.newDocumentBuilder();
Document doc = null;
InputStream is = getClass().getClassLoader().getResourceAsStream("/payLoadXML.xml");
doc = docBuilder.parse(is);
Node staff = doc.getElementsByTagName("m:properties").item(0);
Text givenNameValue = doc.createTextNode("abc");
Element givenName = doc.createElement("d:GivenName");
givenName.appendChild(givenNameValue);
staff.appendChild(givenName);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = null;
transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
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?
I'd like to serialize some simple data model into xml, I've been using the standard java.org.w3c -related code (see below), the indentation is better than no "OutputKeys.INDENT", yet there is one little thing that remains - proper indentation for child elements.
I know that this has been asked before on stackoverflow , yet that configuration did not work for me, this is the code I'm using :
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
doc = addItemsToDocument(doc);
// The addItemsToDocument method adds childElements to the document.
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", new Integer(4));
// switching to setAttribute("indent-number", 4); doesn't help
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(outFile);
// outFile is a regular File outFile = new File("some/path/foo.xml");
transformer.transform(source, result);
The output produced is :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<stuffcontainer>
<stuff description="something" duration="240" title="abc">
<otherstuff />
</stuff>
</stuffcontainer>
Whereas I would want it (for more clarity) like :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<stuffcontainer>
<stuff description="something" duration="240" title="abc">
<otherstuff />
</stuff>
</stuffcontainer>
I was just wondering if there is a way of doing this, make it properly indented for the child elements.
Thank you in advance !
Happy Easter coding :-) !
If the Transformer implementation you're using is Xalan-J, then you should be able to use:
transformer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "5");
See also: http://xml.apache.org/xalan-j/usagepatterns.html
import com.sun.org.apache.xml.internal.serializer.OutputPropertiesFactory
transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "4");
Document doc;
.....
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(new DOMSource(doc), new StreamResult(new File("filename.xml")));
transformer.transform(new DOMSource(doc), new StreamResult(System.out));