java.net.MalformedURLException: Protocol not found. Reason? - java

I am using this function :
public void testing(String xml) throws ParserConfigurationException, SAXException, IOException{
Log.d("TAG"," root.getNodeName()");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xml);
//document.getDocumentElement().normalize();
//Element root = document.getDocumentElement();
//Log.d("TAG", root.getNodeName());
Log.d("TAG"," root.getNodeName()");
}
And I am calling this function like this :
testing(responseText)
Where response text is this:
<?xml version='1.0' encoding='UTF-8'?>
<queryresult success='true'
error='false'
numpods='2'
datatypes=''
timedout=''
timedoutpods=''
timing='0.751'
parsetiming='0.216'
parsetimedout='false'
recalculate='http://www4b.wolframalpha.com/api/v2/recalc.jsp?id=MSPa2715236aaf6db55age00000025hbhc18c61h80c4&s=10'
id='MSPa2716236aaf6db55age00000019f566b957ic219h'
host='http://www4b.wolframalpha.com'
server='10'
related='http://www4b.wolframalpha.com/api/v2/relatedQueries.jsp?id=MSPa2717236aaf6db55age000000535a701459c5c90a&s=10'
version='2.6'>
<pod title='Input interpretation'
scanner='Identity'
id='Input'
position='100'
error='false'
numsubpods='1'>
<subpod title=''>
<plaintext>Tell me a joke.</plaintext>
</subpod>
</pod>
<pod title='Result'
scanner='Data'
id='Result'
position='200'
But im getting the error:
04-06 22:19:14.348: D/TAG(30413): java.net.MalformedURLException:
Protocol not found:
What am I doing wrong ?
Note that I am getting this responseText from a server. So if theres any problem with the xml itself, do tell me how to manipulate the string, instead of suggesting me to change the xml itself.

The problem is that you're passing in the XML content itself - but DocumentBuilder.parse(String) accepts a URL to load the XML from - not the content itself.
You probably want to use DocumentBuilder.parse(InputSource) instead, having created an InputSource from a StringReader wrapping the XML:
Document document = builder.parse(new InputSource(new StringReader(xml)));

Related

Trying to convert xml string into a document object, getting error through IDE

I have been trying to convert an xml string into a document so I can later add a node, I have found the same solution in 5 different places however my IDE is giving me an error. The error reads as "the method parse(inputstream)in type DocumentBuilder is not applicable for the arguments(inputSource)."
I have tried the exact code multiple times including choosing the right method output, but I keep getting the same error.
private static Document converStringToDocument(String xml) {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new InputSource(new StringReader(xml)));
return document;
}
I want this to return a document so I can add a node.

how to parse and get data from xml in java

I have this XML code:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="https://www.cvlkra.com/">tTKyEndh0iBqnZdjpUntEQ%3d%3d</string>
I want to get this: tTKyEndh0iBqnZdjpUntEQ%3d%3d for which I have tried the below code:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder1 = factory.newDocumentBuilder();
Document document = builder1.parse(new InputSource(new StringReader(string)));
Element rootElement = document.getDocumentElement();
String nodeName = rootElement.getNodeName();
But i am not getting it. I am getting null value instead of tTKyEndh0iBqnZdjpUntEQ%3d%3d even when I have tried some other code also.
Try using getTextContent() instead getNodeValue() returns null because it has no values.
You should not use getNodeName() instead use rootElement.getNodeValue(). May be this helps.

Parsing xml in Android without xml declaration using SAX

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.

Xml Document Read attempt error

In my software I'm trying to create a class that returns any bit of an xml file, take a look at the code and the error its giving me, i cant figure out how to correct it :(
Xml :
<everConfigured>
<value>false</value>
</everConfigured>
<ServerPort>
<value>9000</value>
</ServerPort>
<ClientPort>
<value>8000</value>
</ClientPort>
XML Reader Class :
public static String getValue(String Path,String Tag,String Atribute) throws IOException, SAXException, ParserConfigurationException
{
File fXmlFile = new File(Path);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName(Tag);
Node nNode = nList.item(0);
Element eElement = (Element) nNode;
return eElement.getAttribute(Atribute);
}
And here is how I called it :
public static void main(String[] args) throws SocketException, IOException, SAXException, ParserConfigurationException {
System.out.println(
XMLRead.getValue("/home/ghhwer/Desktop/settings.xml", "everConfigured","value"));
}
but returns this error :
[Fatal Error] settings.xml:5:2: The markup in the document following the root element must be well-formed.
Exception in thread "main" org.xml.sax.SAXParseException; systemId: file:/home/ghhwer/Desktop/settings.xml; lineNumber: 5; columnNumber: 2; The markup in the document following the root element must be well-formed.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:257)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:348)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:205)
at program.XMLRead.getValue(XMLRead.java:20)
at program.Start.main(Start.java:12)
The markup in the document following the root element must be well-formed.
There are several rules for XML to be well-formed:
All XML Elements Must Have a Closing Tag;
Tags should be in the same case;
XML Elements Must be Properly Nested;
XML Documents Must Have a Root Element;
XML Attribute Values Must be Quoted;
Some symbols have special meaning and have to be escaped (>, <, &, ', ").
In provided XML snippet root element is missing, that is why parser complains.
So, well-formed XML will be:
<?xml version="1.0" encoding="UTF-8"?>
<config>
<everConfigured>
<value>false</value>
</everConfigured>
<ServerPort>
<value>9000</value>
</ServerPort>
<ClientPort>
<value>8000</value>
</ClientPort>
</config>
See http://www.w3schools.com/xml/xml_syntax.asp as XML syntax reference.
I think the problem is that in XML there can be only one root element, but you have three.
You have to restructure you file to something like:
<?xml version="1.0" encoding="UTF-8"?>
<OneRootElement>
<everConfigured>
<value>false</value>
</everConfigured>
<ServerPort>
<value>9000</value>
</ServerPort>
<ClientPort>
<value>8000</value>
</ClientPort>
</oneRootElement>
The error about well-formed XML on the root level should disappear
The problem is an XML validation error, to fix it run the file through an online validation tool like http://www.xmlvalidation.com/ or validate it using the IDE.
The tool will pinpoint the cause better, in this case it seems to be a problem of not well formed XML.

How can i convert a string into xml in JAVA which contains one attribute having value with angular brackets

I got a situation when i need to convert my string into xml which contains
"CGNAME="<Input>GROUP1</Input>"
"<SOLRQUERY><I M="1" V="(1:2)OR(62:12)" CGNAME="<Input>GROUP1</Input>" BSLFLG="0" /></SOLRQUERY>"
in parameter I am passing above string
String escaped = StringEscapeUtils.escapeJava(value);
Document CGXml = XPathReader.StringToXMLDocument(escaped);
And i am getting following error:
org.xml.sax.SAXParseException: Open quote is expected for attribute
XPathReader is my inBuilt class and StringToXMLDocument function code i am putting.
public static Document StringToXMLDocument(String criteriaXML) throws ParserConfigurationException, SAXException, IOException
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource isCriteriaXML = new InputSource();
isCriteriaXML.setCharacterStream(new StringReader(criteriaXML));
Document doc = db.parse(isCriteriaXML);
doc.getDocumentElement().normalize();
return doc;
}
You can escape your characters. This means add \ before your "
For example:
CGNAME\"=\"GROUP1\"
So your String query would be:
"<SOLRQUERY>
<I M=\"1\" V=\"(1:2)OR(62:12)\" CGNAME=\"<Input>GROUP1</Input>\" BSLFLG=\"0\" />
</SOLRQUERY>"

Categories