how to create xml file in runtime? - java

I am trying to create an XML file at run-time under my web content folder, but a No such file or directory error was displayed.
My code:
Document document = DocumentHelper.createDocument();
Element rootElement = document.addElement("Students");
Element studentElement = rootElement.addElement("student").addAttribute("country", "USA");
studentElement.addElement("id").addText("1");
studentElement.addElement("name").addText("Peter");
XMLWriter writer = new XMLWriter(new FileWriter("/WebContent/Students.xml"));
//Note that You can format this XML document
/*
* FileWriter output = new FileWriter(new File("Students.xml"));
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(output,format);<- will fomat the output
*/
//You can print this to the console and see what it looks like
String xmlElement = document.asXML();
System.out.println(xmlElement);
writer.write(document);
writer.close();
I don't know how to do this. Can anyone help me to fix my code?

i got the answer i just change the path from /WebContent/Students.xml to
WebContent/Students.xml.
just remove the / before the WebContent

Related

JDOM get string of containing content

lets say I have some xml:
<document>blabla<bold>test<list><item>hello<italics>dfh</italics></item></list></bold>sdfsd</document>
and I now need to get the content of as a string, so I would have
blabla<bold>test<list><item>hello<italics>dfh</italics></item></list></bold>sdfsd
i have been messing with this in my head for a while now, and I haven't seem to be able to figure it out.
Hope to get some directions to what I have to do.
EDIT:
just to be clear, lets say I have the XML like this:
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(new StringReader("<document>blabla<bold>test<list><item>hello<italics>dfh</italics></item></list></bold>sdfsd</document>"));
and I now need to get the content of
It is very unusual to need to get an inconsistent subset of an XML document like you want. It's much more common to get just the text content: blabla test hello dfh sdfsd
Note that you can get a subset of the content as the "contentlist" of the root element, and then output just that list as a string:
XMLOutputter xout = new XMLOutputter();
String txt = xout.outputString(doc.getRootElement().getContent());
System.out.println(txt);
For me, I wrote the code:
public static void main(String[] args) throws JDOMException, IOException {
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(new StringReader("<document>blabla<bold>test<list><item>hello<italics>dfh</italics></item></list></bold>sdfsd</document>"));
XMLOutputter xout = new XMLOutputter();
String txt = xout.outputString(doc.getRootElement().getContent());
System.out.println(txt);
}
and it output:
blabla<bold>test<list><item>hello<italics>dfh</italics></item></list></bold>sdfsd

JAVA XMLOutPuter changing values of other nodes in XML document

I am using the below method to produce an XML document using getFile() to get the same file as my SAXBuilder.
SAXBuilder reader = new SAXBuilder();
Document document = reader.build(new File(file)); //file example: Desktop/test.camproj (which is an XML document)
When I write the file I use the below code. I only change one value in the XML document (which works), but when I open up this video (this xml file is a video file) all the values of all nodes of type Callout have been changed to their defaults. Is this the correct way of creating the file or am I doing something wrong? If I don't open the video and open the file in Notepad nothing except the node I change was altered.
XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());
FileOutputStream output = new FileOutputStream(getFile());
xmlOutput.output(document, output);
document.detachRootElement();
output.close();
My change to the xml node (I am using /n/r to represent line breaks in XML):
newText = "{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033{\\fonttbl{\\f0\\fswiss\\fprq2\\fcharset0 Open Sans"
+ ";}}\n\r{\\colortbl ;\\red0\\green0\\blue0;}\n\r\\viewkind4\\uc1\\pard\\qc\\cf1\\f0\\fs36 " + newText + "\\par\n\r}\n\r;";
document.getRootElement().getChild("CSMLData").getChild("GoProject").getChild("Project")
.getChild("Timeline").getChild("GenericMixer").getChild("Tracks").getChildren().get(index2).getChild("Medias").getChildren().get(index)
.getChild("Attributes").getChild("Attribute").getChild("VectorNode").getChild("StringParameters")
.getChildren().get(3).getChild("Keyframes").getChild("Keyframe").setAttribute("value", newText);

Dom4j get single node text value

Assume I have
<Sports>
<Soccer>
<Players>
<Player_1> Messi Leonel </Player_1>
</Players>
</Soccer>
</Sports>
How to get Player_1 node text in one line without iteration using Dom4J?
Return value should be: Messi Leonel
Thanks
Got it, to the person who looks something like this
File file = new File("/path/to/file.xml");
SAXReader reader = new SAXReader();
Document document = reader.read(file);
String name = document.selectSingleNode("//Sports/Soccer/Players/Player_1").getText();

How to switch java code from using local XML file to URL of an XML file

I have written web application that reads an XMl file parses it and does some work.
Rather than using a local file, I'd like to use a URL of the XML file ( something like http://mydomain.com/daily-extract.xml )
This is what my code looks like:
private String xmlFile = "D:\\default-user\\WINXP\\Desktop\\extract-jan10d.xml";
SAXBuilder builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser");
// Parse the specified file and convert it to a JDOM document
document = builder.build(new File(xmlFile));
Element root = document.getRootElement();
How can I switch from a file to a URL on the internet
Try to replace this line :
document = builder.build(new File(xmlFile));
By :
document = builder.build(new File(new URI("http://mydomain.com/daily-extract.xml")));

How to save parsed and changed DOM document in xml file?

I have xml-file. I need to read it, make some changes and write new changed version to some new destination.
I managed to read, parse and patch this file (with DocumentBuilderFactory, DocumentBuilder, Document and so on).
But I cannot find a way how to save that file. Is there a way to get it's plain text view (as String) or any better way?
Something like this works:
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Result output = new StreamResult(new File("output.xml"));
Source input = new DOMSource(myDocument);
transformer.transform(input, output);
That will work, provided you're using xerces-j:
public void serialise(org.w3c.dom.Document document) {
java.io.ByteArrayOutputStream data = new java.io.ByteArrayOutputStream();
java.io.PrintStream ps = new java.io.PrintStream(data);
org.apache.xml.serialize.OutputFormat of =
new org.apache.xml.serialize.OutputFormat("XML", "ISO-8859-1", true);
of.setIndent(1);
of.setIndenting(true);
org.apache.xml.serialize.XMLSerializer serializer =
new org.apache.xml.serialize.XMLSerializer(ps, of);
// As a DOM Serializer
serializer.asDOMSerializer();
serializer.serialize(document);
return data.toString();
}
That will give you possibility to define xml format
new XMLWriter(new FileOutputStream(fileName),
new OutputFormat(){{
setEncoding("UTF-8");
setIndent(" ");
setTrimText(false);
setNewlines(true);
setPadText(true);
}}).write(document);

Categories

Resources