Reading multiple xml file in a folder - java

The code I posted is all working and is for writing but I need advice for how do I read the xml file so I can output it and/or delete the file. I read about SAX, documentbuilder .parse method and few others but I am confused on what do I use. I do not need you to write code for this but to point me in right direction.
The files are created in a folder separately so I need to read them all at once if possible (the name of the file is the variable listed below as Id)
This is how I create XML files.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
{
try {
DocumentBuilder doc = factory.newDocumentBuilder();
Document doc1=doc.newDocument();
Element IdNumber = (Element) doc1.createElement(Id);
Element IDes=(Element) doc1.createElement("InitialDestination");
Element FinDes=(Element) doc1.createElement("FinalDestination");
Element HourTime=(Element) doc1.createElement("Hours");
Element Minutetime=(Element) doc1.createElement("Minutes");
Element Price=(Element) doc1.createElement("TicketPrice");
Element Tran=(Element) doc1.createElement("TransportAgency");
doc1.appendChild(IdNumber);
IDes.appendChild(doc1.createTextNode(InDes));
FinDes.appendChild(doc1.createTextNode(FDes));
HourTime.appendChild(doc1.createTextNode(Htime));
Minutetime.appendChild(doc1.createTextNode(Mtime));
Price.appendChild(doc1.createTextNode(TicketPrice));
Tran.appendChild(doc1.createTextNode(TransportAgency));
IdNumber.appendChild(IDes);
IdNumber.appendChild(FinDes);
IdNumber.appendChild(HourTime);
IdNumber.appendChild(Minutetime);
IdNumber.appendChild(Price);
IdNumber.appendChild(Tran);
Source S=new DOMSource(doc1);
File file1=new File("C:\\Users\\Lozanovski\\Desktop\\TransportMe");
file1.mkdirs();
File file=new File("C:\\Users\\Lozanovski\\Desktop\\TransportMe\\"+Id+".xml");
StreamResult R=new StreamResult(file);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(S, R);
}
catch(ParserConfigurationException except)
{
System.out.println(except);
}
catch(TransformerException except1)
{
System.out.println(except1);
}
catch(DOMException except2)
{
System.out.println(except2);
}
catch(NullPointerException except3){
System.out.println(except3);
}
}
I don't know how to properly post xml code (I will accept edit)
<?xml version="1.0" encoding="UTF-8"?>
-<InsertIdentificationNumber>
<InitialDestination>Insert Initial Destination</InitialDestination>
<FinalDestination>Insert Final Destination</FinalDestination>
<Hours>Insert Hours</Hours>
<Minutes>Insert Minutes</Minutes>
<TicketPrice>Insert Ticket Price</TicketPrice>
<TransportAgency>Insert Transport Agency</TransportAgency>
</InsertIdentificationNumber>

Loop through the folder, and for each file found, create a Document and use it to display/output the content. You can also delete the file if needed:
File folder = new File("C:\\Users\\Lozanovski\\Desktop\\TransportMe");
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
if (folder.isDirectory()) {
for (File file : folder.listFiles()) {
Document doc = docBuilder.parse(file); // create an XML document
file.delete(); // delete the file
}
}

Related

Link XML and XSD using java

i'm trying to write the header for an xml file so it would be something like this:
<file xmlns="http://my_namespace"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://my_namespace file.xsd">
however, I can't seem to find how to do it using the Document class in java. This is what I have:
public void exportToXML() {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.newDocument();
doc.setXmlStandalone(true);
doc.createTextNode("<file xmlns=\"http://my_namespace"\n" +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
"xsi:schemaLocation=\"http://my_namespace file.xsd\">");
Element mainRootElement = doc.createElement("MainRootElement");
doc.appendChild(mainRootElement);
for(int i = 0; i < tipoDadosParaExportar.length; i++) {
mainRootElement.appendChild(criarFilhos(doc, tipoDadosParaExportar[i]));
}
Transformer tr = TransformerFactory.newInstance().newTransformer();
tr.transform(new DOMSource(doc),
new StreamResult(new FileOutputStream(filename)));
} catch (Exception e) {
e.printStackTrace();
}
}
I tried writing it on the file using the createTextNode but it didn't work either, it only writes the version before showing the elements.
PrintStartXMLFile
Would appreciate if you could help me. Have a nice day
Your createTextNode() method is only suitable for creating text nodes, it's not suitable for creating elements. You need to use createElement() for this. If you're doing this by building a tree, then you need to build nodes, you can't write lexical markup.
I'm not sure what MainRootElement is supposed to be; you've only given a fragment of your desired output so it's hard to tell.
Creating a DOM tree and then serializing it is a pretty laborious way of constructing an XML file. Using something like an XMLEventWriter is easier. But to be honest, I got frustrated by all the existing approaches and wrote a new library for the purpose as part of Saxon 10. It's called simply "Push", and looks something like this:
Processor proc = new Processor();
Serializer serializer = proc.newSerializer(new File(fileName));
Push push = proc.newPush(serializer);
Document doc = push.document(true);
doc.setDefaultNamespace("http://my_namespace");
Element root = doc.element("root")
.attribute(new QName("xsi", "http://www.w3.org/2001/XMLSchema-instance", "schemaLocation"),
"http://my_namespace file.xsd");
doc.close();

How to Read/Write to an xml file?

I have an xml file already created that has tags and values for the tags.
<?xml version="1.0" encoding="utf-16"?>
<Scoreboard>
<Score>
<username>Ryan</username>
<points>200</points>
</Score>
All I want to be able to do is read the information within the tags as well as write tot he already created xml document with a new tag. If i wanted to add username: Andrew, points: 100, how would i accomplish this? In addition how could i read the xml file so that i could display all the scores and its information?
Read - InputStream is = getAssets().open("highscores2.xml");
DocumentBuilderFactory dbFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
Element element = doc.getDocumentElement();
element.normalize();
write - InputStream is = getAssets().open("highscores2.xml");
DocumentBuilderFactory dbFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
NodeList nodes = doc.getElementsByTagName("Score");
Text a = doc.createTextNode("Dylly");
Element p = doc.createElement("username");
p.appendChild(a);
nodes.item(0).getParentNode().insertBefore(p, nodes.item(0));
As of right now I have my xml file stored in an asset folder but when i try to write to it I am given an error - saying it is read only. How can I get around this as well?
Any help would be greatly appreciated, I have spent all afternoon trying to find a solution to this problem and have come up with almost nothing, thanks.
There's a class for writing an xml file:
serializer = Xml.newSerializer();
writer = new StringWriter();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", true);
serializer.setPrefix(prefix, namespace);
serializer.startTag(prefix, tagName);
serializer.attribute(prefix, attrName, value);
serializer.endTag(prefix, tagName);
serializer.endDocument();
return writer.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
And even for reading an xml file:
XmlPullParserFactory xmlPullParserFactory = XmlPullParserFactory.newInstance();
xmlPullParserFactory.setNamespaceAware(true);
XmlPullParser xmlPullParser = xmlPullParserFactory.newPullParser();
xmlPullParser.setInput(new StringReader(xml));
return xmlPullParser;

Why IDE and console is doing different operation about xml files in Java?

I am newbie in XML files operation. My program should do that when it is executed, it must generate random numbers and write to a XML file. Every time when I debug it in NetBeans IDE everything is okay, but when I try execute it in console with "Java -jar blablabla.jar" the XML files are not changing and I still see old values in XML files. Why is that happen? Why can IDE modify the values in XML while console cannot?
Here is my XML operations code block:
public class CreateXML {
public CreateXML(ArrayList<Integer> array,String name){
try{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
String path="file"+name+".xml";
File xmlfile=new File(path);
if(xmlfile.exists()){
xmlfile.delete();
System.out.println("There was this file and it is deleted.");
}
Document doc=db.newDocument();
Element rootElement=doc.createElement("numberList");
doc.appendChild(rootElement);
for (int i = 0; i < array.size(); i++) {
Element staff=doc.createElement("number");
rootElement.appendChild(staff);
Attr attr=doc.createAttribute("id");
attr.setValue(Integer.toString(i));
staff.setAttributeNode(attr);
staff.setTextContent(Integer.toString(array.get(i)));
}
TransformerFactory tf=TransformerFactory.newInstance();
Transformer t=tf.newTransformer();
DOMSource source=new DOMSource(doc);
StreamResult result=new StreamResult(xmlfile);
t.transform(source, result);
}catch(Exception e){
e.printStackTrace();
}
}
}

Replace text in XML before XSLT

I need to replace a certain text in a XML file before giving it to the XSL-Transformer.
It's the DTD-URL in the DOCTYPE tag. It points to a webserver, but I want it to be usable offline, so I want to change it to a URL pointing to a local file.
However I mustn't edit the original XML directly. I thought of reading the file into a string, use String.replaceAll() on the text and save it into another file, which I pass to the Transformer. I already tried it, but it's really slow; the file I'm using has a size of ca. 500kiB.
Is there any better (=faster) way to accomplish this?
EDIT: The code used for the transformation:
public String getPlaylist(String playlist) {
Source source = new StreamSource(library);
StreamSource xsl = new StreamSource(getClass().getResourceAsStream("M3Utransformation.xml"));
StringWriter w = new StringWriter();
Result result = new StreamResult(w);
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer(xsl);
transformer.setParameter("playlist", playlist);
transformer.transform(source, result);
return w.getBuffer().toString();
} catch (Throwable t) {
t.printStackTrace();
return null;
}
}
You can create an entity resolver, and make use of it.
The following example uses the JAXP DocumentBuilder, and a CatalogResolver
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException, TransformerConfigurationException, TransformerException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
db.setEntityResolver(new CatalogResolver());
File src = new File("src/article.xml");
Document doc = db.parse(src);
// Here, we execute the transformation
// Use a Transformer for output
File stylesheet = new File("src/aticle.xsl");
TransformerFactory tFactory = TransformerFactory.newInstance();
StreamSource stylesource = new StreamSource(stylesheet);
Transformer transformer = tFactory.newTransformer(stylesource);
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
}
create a catalog properties file, and place it on your classpath
CatalogManager.properties has to be the name, see CatalogManager API documentation
define a catalog XML file, point your properties file, above to it. From
http://www.xml.com/pub/a/2004/03/03/catalogs.html you can find a very simple catalog XML file :
<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
<public publicId="-//OYRM/foo" uri="src/bar.dtd"/>
</catalog>
With the above catalog.xml and CatalogManager.properties, you'll end up resolving references to the publicId "-//OYRM/foo" to the uri src/bar.dtd
xml-commons contains the resolver :
http://xerces.apache.org/mirrors.cgi#binary
for a more complete treatment of the topic of Resolvers read Tom White's article from XML.com
The transformer application was cribbed from the Java trail for Extensible StyleSheet Language Transformations > Transforming Data with XSLT

Cannot run Xpath queries from JAVA in XML files having <DOCTYPE> tag

I have made the following method which runs hard-coded xPath queries in a hard-coded XML file. The method works perfect with one exception. Some xml files contains the following tag
<!DOCTYPE WorkFlowDefinition SYSTEM "wfdef4.dtd">
When i try to run a query in that file i get the following exception:
java.io.FileNotFoundException:
C:\ProgramFiles\code\other\xPath\wfdef4.dtd(The system cannot find the file specified).
The question is : What can i do to instruct my program not to take under consideration this DTD file?
I have also noted that the path C:\ProgramFiles\code\other\xPath\wfdef4.dtd is the one i run my application from and not the one that the actual xml file is located.
Thank you in advace
Here is my method:
public String evaluate(String expression,File file){
XPathFactory factory = XPathFactory.newInstance();
xPath = XPathFactory.newInstance().newXPath();
StringBuffer strBuffer = new StringBuffer();
try{
InputSource inputSource = new InputSource(new FileInputStream(file));
//evaluates the expression
NodeList nodeList = (NodeList)xPath.evaluate(expression,
inputSource,XPathConstants.NODESET);
//does other stuff, irrelevant with my question.
for (int i = 0 ; i <nodeList.getLength(); i++){
strBuffer.append(nodeList.item(i).getTextContent());
}
}catch (Exception e) {
e.printStackTrace();
}
return strBuffer.toString();
}
And the answer is :
xPath = XPathFactory.newInstance().newXPath();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//add this line to ignore dth DTD
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

Categories