Unable to read an uploaded multipart xml file - java

I am trying to write a service that receives a xml file and parses it and does some additional processing.
At the UI controller I converted the multipart file contents to a string and passed it to the service.
From the UI controller - I upload the file and call the service method to parse the xml file
MultipartFile newFile=multiPartRequest.getFile("newFileUpload");
String fileContent = new String(newFile.getBytes());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(fileContent));
doc = dBuilder.parse(is);
However, doc is always null. What is the best way for me to rest this xml file?

I think its a problem with the
String fileContent String fileContent = new String(newFile.getBytes());
Since not all the bytes of the file are just text , you have the header and eof and bytes that don't represent a text .
What you should do is make a InputStream and build the document off that , like so :
try{
MultipartFile newFile=multiPartRequest.getFile("newFileUpload");
InputStream is = new newFile.getInputStream();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
} catch (SAXException | IOException | ParserConfigurationException ex) {
Logger.getLogger(JavaApplication4.class.getName()).log(Level.SEVERE, null, ex);
}

Related

how to parse XML object in JAVA [duplicate]

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();

I am getting null pointer exception when i get the data from xml document using web service

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));

How to Read/Write to an xml file?

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;

Use a Remote XML as File [duplicate]

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();

In Java, how do I parse XML as a String instead of a file?

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();

Categories