Why I am always getting this error.I am trying to append data to existing xml file.I read here the answer and tried what was suggested.
But still no success.I know this error mean that the top root element can
only come once.But why I am getting this error I don’t know.
This will be the structure of my xml file.
<root>
<ip>ip1</ip>
<ip>ip2</ip>
</root>
And the ip tag will keep on increasing.Here’s how I am trying to read and append data to existing file.
private void UpdateExistingXML(String ip,File file)
{
try
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(file.toURI().toString()); // <--error here
// Get the root element
Node root= doc.getFirstChild();
org.w3c.dom.Element newip=doc.createElement("ip");
newip.appendChild(doc.createTextNode(ip));
root.appendChild(newip);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(file);
transformer.transform(source, result);
}
catch (ParserConfigurationException pce)
{
pce.printStackTrace();
}
catch (TransformerException tfe)
{
tfe.printStackTrace();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
catch (SAXException sae)
{
sae.printStackTrace();
}
catch (Exception e)
{
Log.e("eeee",e.getMessage());
}
}
Here’s how I am creating the xml file for the first time which shows the root element is only inserted once.
private void CreateNewXML(String ip) throws FileNotFoundException
{
FileOutputStream fos=null ;
Log.i("Fileeee","new");
try
{
fos = openFileOutput("clients.xml", Context.MODE_PRIVATE);
}
catch(FileNotFoundException e)
{
Log.e("FileNotFoundException", "can't create FileOutputStream");
}
XmlSerializer serializer = Xml.newSerializer();
try {
serializer.setOutput(fos, "UTF-8");
serializer.startDocument(null, Boolean.valueOf(true));
serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
serializer.startTag(null, "root");
serializer.startTag(null, "ip");
serializer.text(ip);
serializer.endTag(null, "ip");
serializer.endTag(null, "root");
serializer.endDocument();
serializer.flush();
fos.close();
}
catch (Exception e)
{
Log.e("Exceptionhaiiiiiiiiiii",e.getMessage());
}
}
This looks like your problem:
You are trying to parse the file path, rather than the file. You need to create an
inputStreamand parse that.If you are getting the file from a web server it might look like this: