Am using DocumentBuilderFactory to read an XML file and write the same file with different file name. Here's my code :
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(new InputSource("internal.xml"));
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(dom);
StreamResult result = new StreamResult(new File("newInternal.xml"));
transformer.transform(source, result);
System.out.println("File Saved!!!");
But am experiencing error in 'newInternal.xml' file. It's saving with '<' , '>' in the new file. May I know the issue with the above code ?
But it's working fine when I changed the Xml version from 1.1 to 1.0.
Your code is correct.
On correct XML syntax, you write < to represent a < and > to represent a >.
These escapings exists to ease their utilization, because the characters are used on the XML syntax itself.
This question has the list of such characters.
Related
I already created an xml, and i was obliged to modify it using PrintWriter Class. (copying line by line the xml file and modify what i need) but i lost my indentation.
i tried this :
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new InputStreamReader(new FileInputStream(
"notes.xml"))));
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.setOutputProperty(OutputKeys.METHOD, "xml");
xformer.setOutputProperty(OutputKeys.INDENT, "yes");
xformer.setOutputProperty("b;http://xml.apache.org/xsltd;indent-amount", "4");
//xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
Source source = new DOMSource(document);
Result result = new StreamResult(new File("notes.xml"));
xformer.transform(source, result);
but this isn't working : having an exception in the third line :
[Fatal Error] :3:6537: XML document structures must start and end within the same entity.
org.xml.sax.SAXParseException; lineNumber: 3; columnNumber: 6537; XML document structures must start and end within the same entity.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:257)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:347)
So, Is there a way to format an already created XML file in java ?
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 am facing some problem for this following codes
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
//root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("subcompany");
doc.appendChild(rootElement);
//id elements
Element id = doc.createElement("id");
id.appendChild(doc.createTextNode(subCompanyId != null ? subCompanyId : " "));
rootElement.appendChild(id);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
String xmlPath = "/project/MallDirectory/mall";
//EDITED for File creation before writing.
boolean isFileCreated = new File(xmlPath, "subcompany.xml").createNewFile();
System.out.println(isFileCreated);
StreamResult result = new StreamResult(new File(xmlPath, "subcompany.xml"));
transformer.transform(source, result);
} catch (Exception ex) {
ex.printStackTrace();
}
After i run, i get this following error:
javax.xml.transform.TransformerException: java.io.FileNotFoundException: file:/project/MallDirectory/mall/subcompany.xml (No such file or directory)
It used to work on my other project, however not this time round. What exactly went wrong here ?
EDITED:
Here is the path that i am trying to write into. The file is created, but it is empty.
I managed to solve the problem.
Here is the Error:
javax.xml.transform.TransformerException: java.io.FileNotFoundException: file:/project/MallDirectory/mall/subcompany.xml (No such file or directory)
I am thinking maybe the transformer is trying to write the xml to this path 'file:/project/MallDirectory/mall/subcompany.xml'. I don't know how it happened, as i have specifically set the file path '/project/MallDirectory/mall/subcompany.xml', and does not prefixed with 'file:/'.
Therefore, i somehow managed to fix it by doing this:
...
//ERROR CODE:
//StreamResult result = new StreamResult(new File(xmlPath, "subcompany.xml"));
//
StreamResult result = new StreamResult(new File(xmlPath, "subcompany.xml").getPath());
transformer.transform(source, result);
...
The number of files that can be in open state at any point of time is specific to the OS (offcourse ,Can be configured) and you have reached the upper limit of that.Look in the code base of your application ,whehter you have some code that is trying to open a file but not closing the stream after its use.Check for such codes.
The directory path you have defined is incorrect. Take a look at the JavaDoc to determine which form of the directory path you need to get to your file location.
JavaDoc java.io.File
If "/project" is your project name then try "./MallDirectory/mall" else try "./project/MallDirectory/mall". Please observe the string carefully it contains dot in it.
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);