I have a java client and I try to get the XML DOM object from ISBNDB by passing the ISBN number of book. But I get null as the result. But I am able to get the xml when I hit the URL from my browser. Am I doing it in the right way? or Am I completely on a wrong track?
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
System.setProperty("http.proxyHost", "myproxy");
System.setProperty("http.proxyPort", "80");
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL("http://isbndb.com/api/books.xml?access_key=MYKEY&index1=isbn&value1="+isbnValue).openStream());
System.out.println(doc.getTextContent());
} catch (Exception e) {
e.printStackTrace();
}
Related
I have a part of code parsing SVG document.
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(parser);
SVGDocument svgDocument = null;
try {
//svgDocument = factory.createSVGDocument(IMAGE_SVG);
svgDocument = factory.createSVGDocument("file://", new FileInputStream(f
));
} catch (IOException e) {
System.out.println(e.getMessage());
}
NodeList gs= svgDocument.getElementsByTagNameNS("http://www.w3.org/2000/svg","g");
NodeList pathes = svgDocument.getElementsByTagNameNS("http://www.w3.org/2000/svg", "path");
For strange reason gs and pathes bear no nodes inside. While in debugger is see that svgDocument identified elementsById inside it correctly, while elementsByTagNames and elementsByTagNamesNS are empty. How to resolve that issue? How to make elements load by tag name too?
It was some issue with file loading
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setNamespaceAware(true);
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
String line = new String(Files.readAllBytes(Paths.get("path to file")), StandardCharsets.UTF_8);
Document doc = docBuilder.parse(new InputSource(new StringReader(line)));
and that document returns .getElementsByTagNameNS as wanted
The code show this error
SAXParseException: Premature end of file.
when trying to read from this xml file.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL("http://www.bnr.ro/nbrfxrates.xml").openStream());
if(doc!=null){
System.out.print("Not null");
} else {
System.out.print("Null");
}
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;
Here's the XML I'm trying to parse: http://realtime.catabus.com/InfoPoint/rest/routes/get/51
#Override
protected Void doInBackground(String... Url) {
try {
URL url = new URL(Url[0]);
DocumentBuilderFactory dbf = DocumentBuilderFactory
.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Download the XML file
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
// Locate the Tag Name
nodelist = doc.getElementsByTagName("VehicleLocation");
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
During runtime, when it reaches this line: DocumentBuilder db = dbf.newDocumentBuilder(); I get the following error:
Unexpected token (position:TEXT {"RouteId":51,"R...#1:1298 in java.io.InputStreamReader#850b9be)
It seems to have something to do with the encoding. My guess is that it's because the XML doesn't sepcify the encoding, but maybe not.
Is there a way to specify the encoding in the code (I can't change the XML itself)?
Thanks!
EDIT: This seems to only happen when parsing the XML from the url. Storing the file locally seems to work fine.
Is there a way to specify the encoding in the code (I can't change the
XML itself)?
You can call InputSource.setEncoding() to set the encoding.
I would suggest to take a look at XmlPullParser instead for parsing XML in Android.
I am starting an Android application that will parse XML from the web. I've created a few Android apps but they've never involved parsing XML and I was wondering if anyone had any tips on the best way to go about it?
Here's an example:
try {
URL url = new URL(/*your xml url*/);
URLConnection conn = url.openConnection();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());
NodeList nodes = doc.getElementsByTagName(/*tag from xml file*/);
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList title = element.getElementsByTagName(/*item within the tag*/);
Element line = (Element) title.item(0);
phoneNumberList.add(line.getTextContent());
}
}
catch (Exception e) {
e.printStackTrace();
}
In my example, my XML file looks a little like:
<numbers>
<phone>
<string name = "phonenumber1">555-555-5555</string>
</phone>
<phone>
<string name = "phonenumber2">555-555-5555</string>
</phone>
</numbers>
and I would replace /*tag from xml file*/ with "phone" and /*item within the tag*/ with "string".
I always use the w3c dom classes. I have a static helper method that I use to parse the xml data as a string and returns to me a Document object. Where you get the xml data can vary (web, file, etc) but eventually you load it as a string.
something like this...
Document document = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try
{
builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(data));
document = builder.parse(is);
}
catch (SAXException e) { }
catch (IOException e) { }
catch (ParserConfigurationException e) { }
There are different types of parsing mechanisms available, one is SAX Here is SAX parsing example, second is DOM parsing Here is DOM Parsing example.. From your question it is not clear what you want, but these may be good starting points.
There are three types of parsing I know: DOM, SAX and XMLPullParsing.
In my example here you need the URL and the parent node of the XML element.
try {
URL url = new URL("http://www.something.com/something.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList1 = doc.getElementsByTagName("parent node here");
for (int i = 0; i < nodeList1.getLength(); i++) {
Node node = nodeList1.item(i);
}
} catch(Exception e) {
}
Also try this.
I would use the DOM parser, it is not as efficient as SAX, if the XML file is not too large, as it is easier in that case.
I have made just one android App, that involved XML parsing. XML received from a SOAP web service. I used XmlPullParser. The implementation from Xml.newPullParser() had a bug where calls to nextText() did not always advance to the END_TAG as the documentation promised. There is a work around for this.