Parsing Xml file using Java throws Exception. Why? - java

While I was trying to get the attribute of the root element Company I found the following problems, also some exceptions.
But I imported everything I need; then also eclipse says that remove unused import.
I want to know that why it is happening even after i have imported everything,
please give me some idea to remove the bug.
Also is it the way to do xml-parsing? is there any alternative and easy way to
do the same?
import java.io.EOFException;
import java.io.File;
import javax.lang.model.element.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import javax.lang.model.element.Element;
public class DomTest1 {
private static final String file = "test1.xml";
public static void main(String[] args) {
if (args.length>0) {
file = args[0];
}
try {
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document document=builder.parse(new File(file));
Element root=document.getDocumentElement();
System.out.println(root.getTagName());
System.out.printf("name: %s%n", root.getAttribute("name"));
System.out.printf("sHortname: %s%n", root.getAttribute("sHortname"));
System.out.printf("mission : %s%n", root.getAttribute("mission"));
} catch(EOFException e) {
e.printStackTrace();
}
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Type mismatch: cannot convert from org.w3c.dom.Element to javax.lang.model.element.Element
The method getTagName() is undefined for the type Element
The method getAttribute(String) is undefined for the type Element
The method getAttribute(String) is undefined for the type Element
The method getAttribute(String) is undefined for the type Element
at DomTest1.main(DomTest1.java:23)

You have
import javax.lang.model.element.Element;
but you want
import org.w3c.dom.Element;
instead.
Also, regarding this:
also is it the way to do xml-parsing? is there any alternative and
easy way to do the same?
You are using java out of the box-provided ways to do xml parsing. There are several, better alternatives using 3rd part libraries. I'd recommend testing jdom, it is a lot simpler. See example here.

problem is because of this
import javax.lang.model.element.Element;
use this import statement
import org.w3c.dom.Element

Related

I can't throws Exception and IOException in Java

I can't throws Exceptions such as IOException and Exception. I need to add dependencies of these but I couldn't find it.
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException; > It throws error: Cannot resolve symbol 'java' - Add Maven dependency
public class JsoupTest {
public static void main(String[] args) throws IOException { > Cannot resolve symbol 'IOException'
// download the HTML from wikipedia and parses it
final Document document = Jsoup.connect("http://en.wikipedia.org/").get();
// Select a bunch of a tags
final Elements newsHeadLines = document.select("#mp-itn b a");
// Prints to console
for(Element headline : newsHeadLines) { > foreach not applicable to type 'org.jsoup.select.Elements'
System.out.println(headline); > Cannot resolve symbol 'System'
}
}
}
My question can be basic but I'm pretty new on this sorry. If you give my answer please add these:
Where did you find this that dependency?
How can I find dependencies, because I checked Maven repository but I couldn't find.
Compiler throws error even for System.out.println method as I showed above, why is that?
Compiler throws error which I showed on belove, foreach not applicable to type 'org.jsoup.select.Elements'
Thank you for your all answers. I don't want directly dependency. I want it to know why. Thanks
You do not need to add a dependency to use IOException or System.
You probably did not use the compiler correctly or your IDE shows non-existent errors.

Why Are These Imports Errored?

As part of my uni project, I have had to clone a group member's code and work on it myself. But on the imports included below, they are underlined and I can't seem to know why or how to address this. Netbeans says that these are 'Unused imports'. I've already tried to Google this but with no luck.
What does this mean and how do I fix it? Please bear with me as I am completely new to programming and it's concepts. Thank you.
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import static org.apache.http.HttpHeaders.USER_AGENT;
As the name implies, "Unused import" is a message from the IDE (not directly related to Java) and means that you're not using that class/interface/whatever it is. Also, note that this is a warning, not an error. This means, your code can compile and execute without issues.
To fix this, just remove the unused import statements.
Example of how to raise unused import:
package something;
//this interface is never used in this class
import java.util.List;
public class Example {
public static void main(String args[]) {
System.out.println("Hello world");
}
}
Example of how to fix it:
package something;
//removed import java.util.List; since it's not used
public class Example {
public static void main(String args[]) {
System.out.println("Hello world");
}
}

FileReader is already defined in this compilation unit error Java

So I'm working on reading in a ".txt" file to use it to implement Dijkstra's algorithm, but every time I try to compile it gives me a "FileReader is already defined in this compilation unit" error while highlighting where I imported it in the beginning. If I take this out, however, it throws a constructor error when I'm trying to read in the file that it's of the wrong type. What am I missing here??
Here is my code:
import java.io.BufferedReader;
import java.io.File;
//import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class FileReader
{
public ArrayList main1()
{
System.out.println("got here");
try
{
BufferedReader in = new BufferedReader(new FileReader(new File("input1.txt")));
I can provide more if needed, but this is where all of the errors crop up.
Your class is named the same as FileReader in the java.io package (you have commented out above). Rename your class to something else like TextFileReader or InputFileReader or use the fully qualified class name for java.io.FileReader.
Just rename your class "FileReader" to different toxicity, in order not to be confused.

How to check if filesystem supports links and symlinks in Java

The Files class introduced in Java 7 has methods for handling links and symlinks but only as optional operations.
Is there any way of determining at runtime if a file system supports these operations before actually invoking the respective methods or do I need to call them and then catch the exception?
Classes like FileSystem or FileStore do not seem to contain anything in that regard (or I overlooked it).
I don't see any general approach that will work without relying on an UnsupportedOperationException or some other exception.
You could use a heuristic that assumes that only subclasses of BasicFileAttributesView support symbolic linking.
Note: The approach below will not work because FileAttributeViews and file attributes are not the same concept:
I did not get isSymbolicLink as one of the supported attributes with the following code on OS X 10.8.4:
package com.mlbam.internal;
import java.nio.file.Files;
import java.nio.file.FileStore;
import java.nio.file.FileSystems;
import java.nio.file.Paths;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MainClass {
private static final Logger LOG = LoggerFactory.getLogger(MainClass.class);
public static void main(String[] args) {
try {
System.out.println("FileStore.supportsFileAttributeView('isSymbolicLink'): "
+ Files.getFileStore(Paths.get("/")).supportsFileAttributeView("isSymbolicLink"));
// Got: FileStore.supportsFileAttributeView('isSymbolicLink'): false
System.out.println(FileSystems.getDefault().supportedFileAttributeViews());
// Got: [basic, owner, unix, posix]
} catch (Exception e) {}
}
}
Original Answer:
If you have an instance of FileStore, you can use FileStore.supportsFileAttributeView("isSymbolicLink")
Or, if you have an instance of FileSystem, you can check that resulting Set<String> from FileSystem.supportedFileAttributeViews() contains the String "isSymbolicLink".
You can get the FileStore associated with a Path using Files.getFileStore(Path)
One way of getting the FileSystem is via FileSystems.getDefault()

Jruby embedded modules and classes

I have a ruby file as follows:
module Example
class Myclass
def t_st
"Hello World!"
end
end
end
now if this was just a class I would be able to use the following java code:
ScriptEngine jruby = new ScriptEngineManager().getEngineByName("jruby");
jruby.eval(new BufferedReader(new FileReader("example.rb")));
Object example = jruby.eval("Myclass.new");
However, this class rests inside a module. Calling the same code as above produces the error:
Exception in thread "main" org.jruby.embed.EvalFailedException: uninitialized constant myclass
In addition, calling:
Object example = jruby.eval("Example");
The module returns no error. So one would assume this follows the format for Ruby.
Object example = jruby.eval("Example::myclass.new");
Again however, I get the same error as before.
Can anyone help? As there is little documentation on JRuby?
Thanks
Make sure that you do not have syntax errors. Usually I get those errors when I'm not paying attention to what I write...
Secondly, you cannot write the following:
Object example = jruby.eval("Myclass.new");
The reason being that your class is in a module. Instead, use the this:
Object example = jruby.eval("Example::Myclass.new");
Other than that, I don't know what the problem could be. For myself, I was able to run the following code under Java 1.6 and with jruby-engine.jar and jruby-complete-1.4.0.jar under my classpath.
package test;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class MyJavaClass {
public static void main(String arg[]) throws ScriptException,
FileNotFoundException {
ScriptEngine jruby = new ScriptEngineManager().getEngineByName("jruby");
jruby.eval(new BufferedReader(new FileReader("example.rb")));
Object example = jruby.eval("Example::Myclass.new");
jruby.put("a", example);
System.out.println(jruby.eval("$a.t_st"));
}
}

Categories