I want to read DOM document using Stax stream readers and write it using Stax stream writers.
I want to modify xml file and change some element values
I want the cursor to point at a certain element in xml file befor building dom tree
I wrote this code but the xml file did not modified
can anybody help me ?
FileInputStream input = new FileInputStream("cv.xml");
XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(input);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//-*-*- get new entries from input stream
System.out.println("<< CV >>\n -> Modify the first reference\n ** Modify The Name **");
System.out.print(" Enter degree : ");
String degree = in.readLine();
System.out.print(" Enter first name : ");
String fName = in.readLine();
System.out.print(" Enter last name : ");
String lName = in.readLine();
System.out.println(" ** Modify The Address ** ");
System.out.print(" Enter new city : ");
String newCity = in.readLine();
System.out.print(" Enter new country : ");
String newCountry = in.readLine();
//-*-*- let the reader point at the first "reference" element
int eventType;
boolean ref = false, fname = false;
while (reader.hasNext()) {
eventType = reader.next();
switch (eventType) {
case XMLEvent.START_ELEMENT:
if (reader.getLocalName().equalsIgnoreCase("references"))
return;
}
}
//-*-*- build DOM trees using Stax stream reader
Document doc = new DOMConverter().buildDocument(reader);
reader.close();
input.close();
//-*-*- start modification
Element firstRef = (Element)doc.getElementsByTagName("reference").item(0);
NodeList name = (NodeList)firstRef.getElementsByTagName("name");
//-*-*- modify the degree (Dr. , Eng. , Dev. ,etc)
Attr att = (Attr)name.item(0).getAttributes().item(0);
((Node)att).setNodeValue(degree);
//-*-*- modify first name
NodeList firstName = (NodeList)firstRef.getElementsByTagName("fname");
NodeList firstNameChilds = (NodeList)firstName.item(0).getChildNodes();
((Node)firstNameChilds.item(0)).setNodeValue(fName);
//-*-*- modify last name
NodeList lastName = (NodeList)firstRef.getElementsByTagName("lname");
NodeList lastNameChilds = (NodeList)lastName.item(0).getChildNodes();
((Node)lastNameChilds.item(0)).setNodeValue(lName);
//-*-*- modify city
NodeList city = (NodeList)firstRef.getElementsByTagName("city");
NodeList cityChilds = (NodeList)city.item(0).getChildNodes();
((Node)cityChilds.item(0)).setNodeValue(newCity);
//-*-*- modify country
NodeList country = (NodeList)firstRef.getElementsByTagName("country");
NodeList countryChilds = (NodeList)country.item(0).getChildNodes();
((Node)countryChilds.item(0)).setNodeValue(newCountry);
//-*-*- write DOM document
FileOutputStream out = new FileOutputStream("cv.xml");
XMLStreamWriter sw = XMLOutputFactory.newInstance().createXMLStreamWriter(out);
new DOMConverter().writeDocument(doc, sw);
sw.close();
out.close();
It's probably because you are returning when you find the "references" element. Maybe break is what you meant.
Related
I want to create an array of objects per each contestant by using the data stored in a text file which includes the details of the 20 contestants. The project is created in IntelliJ and is a Java Project.
The Text File Looks like this ;
Tom Solesbury ;Molesey BC ;26 ;01:29.4 ;02:58.7 ;04:28.0 ;05:58.3
Marcus Bateman ;Leander Club ;24 ;01:28.9 ;02:58.9 ;04:29.2 ;05:58.2
Evgeni Trofimov ;Marine Technical Uni Russia ;35 ;01:28.2 ;03:01.3
;04:34.5 ;06:02.0
String filePath = "birc.txt";
String line ;
BufferedReader reader = new BufferedReader(new FileReader(filePath));
while ((line = reader.readLine()) != null) {
String[] parts = line.split(";", 7);
name = parts[0];
club = parts[1];
age = Integer.parseInt(parts[2]);
fiveHundred = Time.valueOf(parts[3]);
thousand = Time.valueOf(parts[4]);
thousandFiveHundred = Time.valueOf(parts[5]);
twoThousand = Time.valueOf(parts[6]);
Rower rower;
rower = new Rower();
rower.setName(name);
rower.setClub(club);
rower.setAge(age);
rower.setFiveHundred(fiveHundred);
rower.setThousand(thousand);
rower.setThousandFiveHundred(thousandFiveHundred);
rower.setTwoThousand(twoThousand);
rowerDetails[next[0]++] = rower;
}
reader.close();
this here is not correct:
String line = "";
String[] split = line.split(";");
name = split[0];
club = split[1];
since line is an empty string, split will be init with an empty array.
reading the 1st element or second will cause an exception
I wanted to read specific columns written in my text file and show this specific columns onto my text Area side by side. I manage to read the desired columns and show them to my text area using the codes below:
try
{
ArrayList<String> totalResult1 = new ArrayList<String>();
ArrayList<String> totalResult2 = new ArrayList<String>();
[enter image description here][1]ArrayList<String> totalResult3 = new ArrayList<String>();
try
{
FileInputStream fStream = new FileInputStream("hubo\\" + "table" + ".txt");
DataInputStream in = new DataInputStream(fStream);
BufferedReader br = new BufferedReader (new InputStreamReader(in));
String strLine;
while((strLine = br.readLine()) != null)
{
strLine = strLine.trim();
if((strLine.length()!=0) && (strLine.charAt(0) !='#'))
{
String[] employee = strLine.split("\\s+");
totalResult1.add(employee[0]);
totalResult2.add(employee[1]);
totalResult3.add(employee[2]);
}
}
for(String s1 : totalResult1)
{
showArea.append(s1.toString() + "\n");
}
for(String s2 : totalResult2)
{
showArea.append("\t" + "\t" + s2.toString() + "\n");
}
in.close();
}
catch (Exception e1)
{
}
}
catch(Exception e1)
{
}
This is my result
Alex Santos
Troy Smith
John Love
Married
Single
Married
My desired results are this:
Alex Santos Married
Troy Smith Single
John Love Married
I want to show to my text Area both of my columns side by side, can anyone point me to the right direction.
Your solution is close, but not quite. When you append the employe names from totalResult1 you go to a new line each time. So when you add values from the second list, you are already bellow the names. To create a table like display, you would need to add values from each list at the same time:
for(int i = 0; i < totalResult1.size(); i++){
showArea.append(totalResult1.get(i) + "\t\t");
showArea.append(totalResult2.get(i) + "\n");
}
The should do the trick. But in general, when you want a table you shouldn't use a text area, you can use a table control instead.
I have a program which reads some data under a file reader and then creates an instance of another class which models the data. Anyway that class works (has been tested with some hard coded values) but I now want to output the data of the instance of a Patient being read under the file reader but seem unable to.
Could anyone tell me where i'm going wrong.
You are not adding Patient instances to newPatient collection, that's why it's empty and you are not getting anything printed out. Add elements to queue:
while(scan.hasNextLine()){
String firstname = scan.nextLine();
String surname = scan.nextLine();
String illness = scan.nextLine();
int illnessSeverity = scan.nextInt();
String newLine = scan.nextLine();
newPatient.add(new Patient(firstname,surname,illness,illnessSeverity));
for (Patient newPatientData : newPatient) {
System.out.println(newPatientData);
}
You need to add data first to the Priority Queue. I think you missed that .
PriorityQueue<Patient> newPatient = new PriorityQueue<>();
File fileName = new File("patients.txt");
Scanner scan = null;
try {
scan = new Scanner(fileName);
while(scan.hasNextLine()){
String firstname = scan.nextLine();
String surname = scan.nextLine();
String illness = scan.nextLine();
int illnessSeverity = scan.nextInt();
String newLine = scan.nextLine();
Patient newP = new Patient(firstname,surname,illness,illnessSeverity);
newPatient.add(newP);
}
for (Patient newPatientData : newPatient) {
System.out.println(newPatientData);
}
} catch(Exception e) {
System.out.println("ERROR - file not found");
}
I need to parse XML Tags which are commented out like
<DataType Name="SecureCode" Size="4" Type="NVARCHAR">
<!-- <Validation>
<Regex JavaPattern="^[0-9]*$" JSPattern="^[0-9]*$"/>
</Validation> -->
<UIType Size="4" UITableSize="4"/>
</DataType>
But all I found was setIgnoringComments(boolean)
Document doc = docBuilder.parse(new File(PathChecker.getDataTypesFile()));
docFactory.setIgnoringComments(true); // ture or false, no difference
But it doesn't seem to change anything.
Is there any other way to parse this comments? I have to use DOM.
Regards
Method "setIgnoringComments" removed comments from DOM tree during parsing.
With "setIgnoringComments(false)" you can get comment text like:
NodeList nl = doc.getDocumentElement().getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
if (nl.item(i).getNodeType() == Element.COMMENT_NODE) {
Comment comment=(Comment) nl.item(i);
System.out.println(comment.getData());
}
}
Since there seems not to exist a "regular way" of solving the problem I've just removed the comments.
BufferedReader br = new BufferedReader(new FileReader(new File(PathChecker.getDataTypesFile())));
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(PathChecker.getDataTypesFileWithoutComments())));
String line = "";
while ((line = br.readLine()) != null) {
line = line.replace("<!--", "").replace("-->", "") + "\n";
bw.write(line);
}
Could anybody tell me why I'm getting this error, and how to fix the problem?
Exception in thread "main" java.lang.NoClassDefFoundError: org/codehaus/stax2/ri/Stax2ReaderAdapter
at org.codehaus.staxmate.dom.DOMConverter._build(DOMConverter.java:188)
at org.codehaus.staxmate.dom.DOMConverter.buildDocument(DOMConverter.java:171)
at org.codehaus.staxmate.dom.DOMConverter.buildDocument(DOMConverter.java:152)
at org.codehaus.staxmate.dom.DOMConverter.buildDocument(DOMConverter.java:131)
at xmlprocessing.api.STAXModifyCV.main(STAXModifyCV.java:68)
Caused by: java.lang.ClassNotFoundException: org.codehaus.stax2.ri.Stax2ReaderAdapter
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
... 5 more
Java Result: 1
I wrote the code below:
//-*-*-
FileInputStream input = new FileInputStream("cv.xml");
XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(input);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//-*-*- get new entries from input stream
System.out.println("<< Sahar CV >>\n -> Modify the first reference\n ** Modify The Name **");
System.out.print(" Enter degree : ");
String degree = in.readLine();
System.out.print(" Enter first name : ");
String fName = in.readLine();
System.out.print(" Enter last name : ");
String lName = in.readLine();
System.out.println(" ** Modify The Address ** ");
System.out.print(" Enter new city : ");
String newCity = in.readLine();
System.out.print(" Enter new country : ");
String newCountry = in.readLine();
//-*-*- let the reader point at the first "reference" element
int eventType;
boolean ref = false, fname = false;
while (!ref && reader.hasNext()) {
eventType = reader.next();
switch (eventType) {
case XMLEvent.START_ELEMENT:
if (reader.getLocalName().equalsIgnoreCase("references")) {
ref = true;
break;
}
}
}
System.out.println("I am here");
//-*-*- start modification
Document doc = new DOMConverter().buildDocument(reader);
Element firstRef = (Element)doc.getElementsByTagName("reference").item(0);
NodeList name = (NodeList)firstRef.getElementsByTagName("name");
//-*-*- modify the degree (Dr. , Eng. , Dev. ,etc)
Attr att = (Attr)name.item(0).getAttributes().item(0);
((Node)att).setNodeValue(degree);
//-*-*- modify first name
NodeList firstName = (NodeList)firstRef.getElementsByTagName("fname");
NodeList firstNameChilds = (NodeList)firstName.item(0).getChildNodes();
((Node)firstNameChilds.item(0)).setNodeValue(fName);
//-*-*- modify last name
NodeList lastName = (NodeList)firstRef.getElementsByTagName("lname");
NodeList lastNameChilds = (NodeList)lastName.item(0).getChildNodes();
((Node)lastNameChilds.item(0)).setNodeValue(lName);
//-*-*- modify city
NodeList city = (NodeList)firstRef.getElementsByTagName("city");
NodeList cityChilds = (NodeList)city.item(0).getChildNodes();
((Node)cityChilds.item(0)).setNodeValue(newCity);
//-*-*- modify country
NodeList country = (NodeList)firstRef.getElementsByTagName("country");
NodeList countryChilds = (NodeList)country.item(0).getChildNodes();
((Node)countryChilds.item(0)).setNodeValue(newCountry);
reader.close();
input.close();
//-*-*- write DOM document
FileOutputStream out = new FileOutputStream("cv.xml");
XMLStreamWriter sw = XMLOutputFactory.newInstance().createXMLStreamWriter(out);
new DOMConverter().writeDocument(doc, sw);
sw.close();
out.close();
You need to make sure the right Woodstox is in your path. Basically, you're using a class that's implemented in that jar, but because the jar isn't in the path Java has no idea what class you're referencing.
This means that a .class file was found that didn't contain the expected class, either because the package doesn't correspond with the directory structure or because the file was renamed after compilation. There are other causes but this is the most common.
Sorry I voted down on the 3 answers but suddenly had a doubt and needed to double check what I thought ... and it ended up being more complex than I thought. However I found a very complete answer for you here:
http://mindprod.com/jgloss/runerrormessages.html#NOCLASSDEFFOUNDERROR