I would like to transform a feed to a Document object.
I tried the following code but it seems it's not working with a real feed (uri = null), but it works with an XML file which is already in my computer.
The transform function :
public static Document obtainDocument(String feedurl) {
Document doc = null;
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
URL url = new URL(feedurl);
doc = builder.parse(url.openStream());
...Exceptions...
return doc;
}
EDIT
I'm pretty sure that the URL is right, I use:
String feedurl = "http://feeds2.feedburner.com/Pressecitron";
I tried to use the following code too:
public static Document obtainDocument(String feedurl) {
Document doc = null;
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
URL url = new URL(feedurl);
URLConnection conn = url.openConnection();
doc = builder.parse(conn.getInputStream());
...
return doc;
}
which seems to not works better
And my first version of parser used a String too, but my mate wants me to use a Document (if the connection doesn't work). It worked with the String if I remember well.
Have you tried all the possible ways of using the parse() method ?
Are you sure the URI / URL is correct ?
From the method that you have, you get the feedURL as a String. You can directly pass it to the parse() method and see if that works.
Related
I try to bild document object from string and append it into element but I get exception java.io.FileNotFoundException: project folder path\org.xml.sax.InputSource in this line: Document constantDocument = docBuilder.parse(
String.valueOf(new InputSource( new StringReader( xmlAsString ) )));.
My code looks like this:
Element infoElement = document.createElement("information");
String xmlAsString = "..."; //xml in string format
Document constantDocument = docBuilder.parse(
String.valueOf(new InputSource( new StringReader( xmlAsString ) ))); //java.io.FileNotFoundException
infoElement.appendChild(constantDocument);
What am I missing?
Reason is given here in the Documentation :
public Document parse(String uri)
throws SAXException,
IOException
Parse the content of the given URI as an XML document and return a new
DOM Document object. An IllegalArgumentException is thrown if the URI
is null null.
You are providing a String, and Java is looking to fetch the file at the given String / URI and hence the Exception ...
Based on your attempt, the closest you could use is :
parse(InputSource is)
Parse the content of the given input source as
an XML document and return a new DOM Document object.
So changing the .parse to below should solve your problem :
Document constantDocument = docBuilder.parse(new InputSource(new StringReader(xmlAsString)));
Found what I was looking for:
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader("<root><nod1></node1></root>"));
Document doc = db.parse(is);
I'm trying to parse xml, downloaded from the web, in java, following examples from here (stackoverflow) and other sources.
First I pack the xml in a string:
String xml = getXML(url, logger);
If I printout the xml string at this point:
System.out.println("XML " + xml);
I get a printout of the xml so I'm assuming there is no fault up to this point.
Then I try to create a document that I can evaluate:
InputSource is= new InputSource(new StringReader(xml));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(is);
If I print out the document here:
System.out.println("Doc: " + doc);
I get:
Doc: [#document: null]
When I later try to evaluate expressions with Xpath I get java.lang.NullPointerException and also when just trying to get the length of the root:
System.out.println("Root length " + rootNode.getLength());
which leaves me to believe the document (and later the node) is truly null.
When I try to print out the Input Source or the Node I get eg.
Input Source: org.xml.sax.InputSource#29453f44
which I don't know how to interpret.
Can any one see what I've done wrong or suggest a way forward?
Thanks in advance.
You may need another way to render the document as a string.
For JDOM:
public static String toString(final Document document) {
try {
final ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
final XMLOutputter outp = new XMLOutputter();
outp.output(document, out);
final String string = out.toString("UTF-8");
return string;
}
catch (final Exception e) {
throw new IllegalStateException("Cannot stringify document.", e);
}
}
The output
org.xml.sax.InputSource#29453f44
simply is the class name + the hash code of the instance (as defined in the Object class). It indicates that the class of the instance has toString not overridden.
I am trying to write a code that helps me to create a XML object. For example, I will give a string as input to a function and it will return me a XMLObject.
XMLObject convertToXML(String s) {}
When I was searching on the net, generally I saw examples about creating XML documents. So all the things I saw about creating an XML and write on to a file and create the file. But I have done something like that:
Document document = new Document();
Element child = new Element("snmp");
child.addContent(new Element("snmpType").setText("snmpget"));
child.addContent(new Element("IpAdress").setText("127.0.0.1"));
child.addContent(new Element("OID").setText("1.3.6.1.2.1.1.3.0"));
document.setContent(child);
Do you think it is enough to create an XML object? and also can you please help me how to get data from XML? For example, how can I get the IpAdressfrom that XML?
Thank you all a lot
EDIT 1: Actually now I thought that maybe it would be much easier for me to have a file like base.xml, I will write all basic things into that for example:
<snmp>
<snmpType><snmpType>
<OID></OID>
</snmp>
and then use this file to create a XML object. What do you think about that?
If you can create a string xml you can easily transform it to the xml document object e.g. -
String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><a><b></b><c></c></a>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xmlString)));
} catch (Exception e) {
e.printStackTrace();
}
You can use the document object and xml parsing libraries or xpath to get back the ip address.
try something like
public static Document loadXML(String xml) throws Exception
{
DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
DocumentBuilder bldr = fctr.newDocumentBuilder();
InputSource insrc = new InputSource(new StringReader(xml));
return bldr.parse(insrc);
}
I'm writing an android application, and I would like to get an xml string from web and get all info it contains.
First of all, i get the string (this code works):
URL url = new URL("here my adrress");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String myData = reader.readLine();
reader.close();
Then, I use DOM:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(myData));
Still no problem. When I write
Document doc = db.parse(is);
the application doesn't do anything more. It stops, without errors.
Can someone please tell me what's going on?
I wouldn't know why your code doesn't work since there is no error but I can offer alternatives.
First, I am pretty sure your new InputStream "is" is unnecessary. "parse()" can take "url.openStream()" or "myData" directly as an argument.
Another cause of error could be that your xml data has more than one line(I know you said that the first part of your code worked but I'd rather mention it, just to be sure). If so, "reader.readLine()" will only get you a part of your xml data.
I hope this will help.
Use SAXParser instead of DOM parser. SAXParser is more efficient than DOM parser. Here is two good tutorials on SAXParser
1. http://www.androidpeople.com/android-xml-parsing-tutorial-using-saxparser
2. http://www.anddev.org/parsing_xml_from_the_net_-_using_the_saxparser-t353.html
Use XmlPullParser, it's very fast. Pass in the string from the web and get a hashtable with all the values.
public Hashtable<String, String> parse(String myData) {
XmlPullParser parser = Xml.newPullParser();
Hashtable<String, String> responseFromServer = new Hashtable<String, String>();
try {
parser.setInput(new StringReader (responseString));
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_TAG) {
String currentName = parser.getName();
String currentText = parser.nextText();
if (currentText.trim().length() > 0) {
responseFromServer.put(currentName, currentText);
}
}
eventType = parser.next();
}
} catch (Exception e) {
e.printStackTrace();
}
return responseFromServer;
}
Im reading some RSS from an URL and are experiencing some troubles.
Initially I had a straightforward implementation like this:
SAXReader reader = new SAXReader();
Document doc = reader.read(new URL(sURL));
However, this didnt allow me to timeout the request if the response was very slow. So I changed it to :
public static org.dom4j.Document readXml(InputStream is) throws SAXException, IOException,
ParserConfigurationException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
dbf.setIgnoringComments(false);
dbf.setIgnoringElementContentWhitespace(true);
dbf.setNamespaceAware(true);
DocumentBuilder db = null;
db = dbf.newDocumentBuilder();
return (org.dom4j.Document)db.parse(is);
}
SAXReader reader = new SAXReader();
URL myUrl = new URL(sURL);
URLConnection c = myUrl.openConnection();
c.setConnectTimeout(10000);
c.setReadTimeout(10000);
org.dom4j.Document doc = readXml(c.getInputStream());
Element root = doc.getRootElement();
When trying this, I get a annyoing error:
org.apache.xerces.dom.DeferredDocumentImpl incompatible with org.dom4j.Document
How can I avoid this? None of the above methods are supposed to return that type of Document, and I also try to cast to the correct document type..
EDIT: The problem is db.parse(is) which returns org.w3c.dom ..
Make sure your Element is of type org.dom4j.Element and not org.w3c.dom, javax.bind.xml, etc.
In other words, dom4j API is not compatible with Java's built-in XML API. The two simply do not mix together, unless you operate with Strings (e.g. generate XML in dom4j and parse it with Java's XML or vice versa).
Problem solved!
By using :
DOMReader domReader = new DOMReader();
org.dom4j.Document dom4jDoc = domReader.read(doc);
org.dom4j.Element root = (Element)dom4jDoc.getRootElement();
To create an org.dom4j.Document from the org.w3c.dom.Document