How to Read/Write to an xml file? - java

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;

Related

Batik's SVGDocument.getElementsByTagNameNS returns empty NodeList despite of namespace and tagname being correctly set

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

Get value from xml file www.bnr.ro java

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

Parse a specific XML [duplicate]

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

Unable to read an uploaded multipart xml file

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

Categories