This question already has answers here:
java.net.MalformedURLException: no protocol
(2 answers)
Closed 5 years ago.
I want to parse XML in Java.
The XML looks like:
<Attributes><ProductAttribute ID="359"><ProductAttributeValue><Value>1150</Value></ProductAttributeValue></ProductAttribute><ProductAttribute ID="361"><ProductAttributeValue><Value>1155</Value></ProductAttributeValue></ProductAttribute></Attributes>
My try was:
public static void parseXml(String sb) throws Exception{
sb = "<Attributes><ProductAttribute ID="359"><ProductAttributeValue><Value>1150</Value></ProductAttributeValue></ProductAttribute><ProductAttribute ID="361"><ProductAttributeValue><Value>1155</Value></ProductAttributeValue></ProductAttribute></Attributes>";
Document dom;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.parse(new InputSource(new ByteArrayInputStream(sb.getBytes("utf-8"))));
dom.toString();
}
I wanted first see, if the parsing is going. But it doesn't.
I get the error:
Premature end of file
Have anybody an idea, how can I parse these?
The question is not duplicate. I have read the answers of another question like my question, but the difference is the XML.
Thanks
First parse the JSON string to get the XML, then parse the xml. For instance, using JSON-java:
JSONObject obj = new JSONObject(json);
JSONArray arr = obj.getJSONArray("value");
for (Object elm: arr) {
String xml = ((JSONObject)elm).getString("AttributesXml");
DocumentBuilderFactory documentBuilderFactory
= DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder
= documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(
new InputSource(new StringReader(xml)));
doSomethingWith(document);
}
But the method parse with a String argument expects an URI as the argument, not the XML source, so you must use another one.
UPDATE:
I see that you have updated your question, and the xml is in sb; this will be:
DocumentBuilderFactory documentBuilderFactory
= DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder
= documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(
new InputSource(new StringReader(sb)));
doSomethingWith(document);
Related
I have the following code:
DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
How can I get it to parse XML contained within a String instead of a file?
I have this function in my code base, this should work for you.
public static Document loadXMLFromString(String xml) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
return builder.parse(is);
}
also see this similar question
One way is to use the version of parse that takes an InputSource rather than a file
A SAX InputSource can be constructed from a Reader object. One Reader object is the StringReader
So something like
parse(new InputSource(new StringReader(myString))) may work.
Convert the string to an InputStream and pass it to DocumentBuilder
final InputStream stream = new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8));
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
builder.parse(stream);
EDITIn response to bendin's comment regarding encoding, see shsteimer's answer to this question.
I'm using this method
public Document parseXmlFromString(String xmlString){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream inputStream = new ByteArrayInputStream(xmlString.getBytes());
org.w3c.dom.Document document = builder.parse(inputStream);
return document;
}
javadocs show that the parse method is overloaded.
Create a StringStream or InputSource using your string XML and you should be set.
You can use the Scilca XML Progession package available at GitHub.
XMLIterator xi = new VirtualXML.XMLIterator("<xml />");
XMLReader xr = new XMLReader(xi);
Document d = xr.parseDocument();
String name= "Nsss";
String resulturl ="http://ssss/res/get?sid="+name+"";
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(resulturl));
Document doc = db.parse(resulturl);
System.out.println("sssssssssssssssssssssssssssssssssssssssssssssssssss"+doc.getDoctype().getTextContent());
I am getting this exception.
java.lang.NullPointerException
at com.controller.StudentsResultsController.main(ResultsController.java:130)
You should check to see what the resulturl variable is before you use it, but the other thing you need to address is: You are not using the InputSource at all. The following is likely to work better than what you have:
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(resulturl));
Document doc = db.parse(is);
EDIT
The Fatal Error is caused by the following:
StringReader(resulturl) takes a string argument that must be XML, not a filename or a URL. The parser is reading the value of the string variable, resulturl, and failing immediately because an XML document may not begin with an h character.
Try changing the above to:
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(resulturl));
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;
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to read XML response from a URL in java?
I'm trying to read an XML file from my web server and display the contents of it on a ListView, so I'm reading the file like this:
File xml = new File("http://example.com/feed.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xml);
doc.getDocumentElement().normalize();
NodeList mainNode = doc.getElementsByTagName("article");
// for loop to populate the list...
The problem is that I'm getting this error:
java.io.FileNotFoundException: /http:/mydomainname.com/feed.xml (No such file or directory)
Why I'm having this problem and how to correct it?
File is meant to point to local files.
If you want to point to a remote URI, the easiest is to use the class url
//modified code
URL url = new URL("http://example.com/feed.xml");
URLConnection urlConnection = url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
//your code
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse( in );
As you can see, later on, thanks to java streaming apis, you can easily adapt your code logic to work with the content of the file. This is due to an overload of the parse method in class DocumentBuilder.
You need to use HTTPURLConnection to get xml as input stream and pass it DocumentBuilder, from there you can use the logic you have.
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse resp = client.execute(yourURL);
if(resp.getStatusCode == 200)
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(resp.getEntity().getContent());
}
Note: I just type here, there may be syntax errors.
You need to read the file using a URL object. For instance, try something like this:
URL facultyURL = new URL("http://example.com/feed.xml");
InputStream is = facultyURL.openStream();
I have the following code:
DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
How can I get it to parse XML contained within a String instead of a file?
I have this function in my code base, this should work for you.
public static Document loadXMLFromString(String xml) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
return builder.parse(is);
}
also see this similar question
One way is to use the version of parse that takes an InputSource rather than a file
A SAX InputSource can be constructed from a Reader object. One Reader object is the StringReader
So something like
parse(new InputSource(new StringReader(myString))) may work.
Convert the string to an InputStream and pass it to DocumentBuilder
final InputStream stream = new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8));
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
builder.parse(stream);
EDITIn response to bendin's comment regarding encoding, see shsteimer's answer to this question.
I'm using this method
public Document parseXmlFromString(String xmlString){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream inputStream = new ByteArrayInputStream(xmlString.getBytes());
org.w3c.dom.Document document = builder.parse(inputStream);
return document;
}
javadocs show that the parse method is overloaded.
Create a StringStream or InputSource using your string XML and you should be set.
You can use the Scilca XML Progession package available at GitHub.
XMLIterator xi = new VirtualXML.XMLIterator("<xml />");
XMLReader xr = new XMLReader(xi);
Document d = xr.parseDocument();