How to Read and Write Xml Files

How to read and write XML files?

Here is a quick DOM example that shows how to read and write a simple xml file with its dtd:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE roles SYSTEM "roles.dtd">
<roles>
<role1>User</role1>
<role2>Author</role2>
<role3>Admin</role3>
<role4/>
</roles>

and the dtd:

<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT roles (role1,role2,role3,role4)>
<!ELEMENT role1 (#PCDATA)>
<!ELEMENT role2 (#PCDATA)>
<!ELEMENT role3 (#PCDATA)>
<!ELEMENT role4 (#PCDATA)>

First import these:

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.xml.sax.*;
import org.w3c.dom.*;

Here are a few variables you will need:

private String role1 = null;
private String role2 = null;
private String role3 = null;
private String role4 = null;
private ArrayList<String> rolev;

Here is a reader (String xml is the name of your xml file):

public boolean readXML(String xml) {
rolev = new ArrayList<String>();
Document dom;
// Make an instance of the DocumentBuilderFactory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// use the factory to take an instance of the document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// parse using the builder to get the DOM mapping of the
// XML file
dom = db.parse(xml);

Element doc = dom.getDocumentElement();

role1 = getTextValue(role1, doc, "role1");
if (role1 != null) {
if (!role1.isEmpty())
rolev.add(role1);
}
role2 = getTextValue(role2, doc, "role2");
if (role2 != null) {
if (!role2.isEmpty())
rolev.add(role2);
}
role3 = getTextValue(role3, doc, "role3");
if (role3 != null) {
if (!role3.isEmpty())
rolev.add(role3);
}
role4 = getTextValue(role4, doc, "role4");
if ( role4 != null) {
if (!role4.isEmpty())
rolev.add(role4);
}
return true;

} catch (ParserConfigurationException pce) {
System.out.println(pce.getMessage());
} catch (SAXException se) {
System.out.println(se.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}

return false;
}

And here a writer:

public void saveToXML(String xml) {
Document dom;
Element e = null;

// instance of a DocumentBuilderFactory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// use factory to get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// create instance of DOM
dom = db.newDocument();

// create the root element
Element rootEle = dom.createElement("roles");

// create data elements and place them under root
e = dom.createElement("role1");
e.appendChild(dom.createTextNode(role1));
rootEle.appendChild(e);

e = dom.createElement("role2");
e.appendChild(dom.createTextNode(role2));
rootEle.appendChild(e);

e = dom.createElement("role3");
e.appendChild(dom.createTextNode(role3));
rootEle.appendChild(e);

e = dom.createElement("role4");
e.appendChild(dom.createTextNode(role4));
rootEle.appendChild(e);

dom.appendChild(rootEle);

try {
Transformer tr = TransformerFactory.newInstance().newTransformer();
tr.setOutputProperty(OutputKeys.INDENT, "yes");
tr.setOutputProperty(OutputKeys.METHOD, "xml");
tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tr.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd");
tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

// send DOM to file
tr.transform(new DOMSource(dom),
new StreamResult(new FileOutputStream(xml)));

} catch (TransformerException te) {
System.out.println(te.getMessage());
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
} catch (ParserConfigurationException pce) {
System.out.println("UsersXML: Error trying to instantiate DocumentBuilder " + pce);
}
}

getTextValue is here:

private String getTextValue(String def, Element doc, String tag) {
String value = def;
NodeList nl;
nl = doc.getElementsByTagName(tag);
if (nl.getLength() > 0 && nl.item(0).hasChildNodes()) {
value = nl.item(0).getFirstChild().getNodeValue();
}
return value;
}

Add a few accessors and mutators and you are done!

Read/write to external XML file in Android

Here is the code to write to XML file:

final String xmlFile = "userData";
String userNAme = "username";
String password = "password";
try {
FileOutputStream fos = new FileOutputStream("userData.xml");
FileOutputStream fileos= getApplicationContext().openFileOutput(xmlFile, Context.MODE_PRIVATE);
XmlSerializer xmlSerializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
xmlSerializer.setOutput(writer);
xmlSerializer.startDocument("UTF-8", true);
xmlSerializer.startTag(null, "userData");
xmlSerializer.startTag(null, "userName");
xmlSerializer.text(username_String_Here);
xmlSerializer.endTag(null, "userName");
xmlSerializer.startTag(null,"password");
xmlSerializer.text(password_String);
xmlSerializer.endTag(null, "password");
xmlSerializer.endTag(null, "userData");
xmlSerializer.endDocument();
xmlSerializer.flush();
String dataWrite = writer.toString();
fileos.write(dataWrite.getBytes());
fileos.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

and to read data from XML File the do as below:

final String xmlFile = "userData";
ArrayList<String> userData = new ArrayList<String>();
try {
fis = getApplicationContext().openFileInput(xmlFile);
isr = new InputStreamReader(fis);
inputBuffer = new char[fis.available()];
isr.read(inputBuffer);
data = new String(inputBuffer);
isr.close();
fis.close();
}
catch (FileNotFoundException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
XmlPullParserFactory factory = null;
try {
factory = XmlPullParserFactory.newInstance();
}
catch (XmlPullParserException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
factory.setNamespaceAware(true);
XmlPullParser xpp = null;
try {
xpp = factory.newPullParser();
}
catch (XmlPullParserException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
xpp.setInput(new StringReader(data));
}
catch (XmlPullParserException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int eventType = 0;
try {
eventType = xpp.getEventType();
}
catch (XmlPullParserException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (eventType != XmlPullParser.END_DOCUMENT){
if (eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");
}
else if (eventType == XmlPullParser.START_TAG) {
System.out.println("Start tag "+xpp.getName());
}
else if (eventType == XmlPullParser.END_TAG) {
System.out.println("End tag "+xpp.getName());
}
else if(eventType == XmlPullParser.TEXT) {
userData.add(xpp.getText());
}
try {
eventType = xpp.next();
}
catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String userName = userData.get(0);
String password = userData.get(1);

How to read some contents of xml files and write them into a text file?

You're only calling file.write(sent) once, open the file before the loop, and then add the following line to this code:

file = open(r'file.txt','w')

for item in seg:
sent = item.firstChild.data
print(sent,sep='')
file.write(sent) // <---- this line

file.close()

Read and Write to a XML file using XSLT

Using an XSLT 2.0 processor you can read in the file with the doc function and create a result document using xsl:result-document e.g.

<xsl:template match="AddressFile">
<xsl:result-document href="Names{replace(name, '[^0-9]+', '')}.xml">
<xsl:copy-of select="doc(filepath)//Contact/Name"/>
</xsl:result-document>
</xsl:template>

Note that your expected output lacks a root element containing the Name elements so it is not a well-formed XML document. It is possible to create that result format and my suggestion does that but in most cases it is better to create well-formed XML documents as otherwise there are few ways to read/process the created file with XML tools.

Reading an XML file while it is being written to

When you call

xmlDoc.Save(filePath)

you pass filename, so XmlDocument does not use your fs stream you opened for writing. Instead it opens yet another stream internally, which of course fails because you already have one stream opened for writing.

Instead, seek to the beginning of the stream and then call

xmlDoc.Save(fs);

You may also set stream length to zero before saving (to truncate old contents), though not completely sure irs necessary.

How can I read and write XML documents in OMNeT++?

The problem is that you're not actually changing the file, you're just modifying the internal representation of the XML document. You should actually write that to disk.

If I understand the context of your question correctly, you're trying to generate a trace file that you can later analyze with other tools in an XML format. If that's the case, you should probably write your XML file to disk in your OMNeT++ modules' finish method. The problem is that you're using the OMNeT++ cXML* classes to open your file: these are intended for configuration purposes only, and thus they are read only (see e.g., this entry in the API documentation).

Thus, I recommend that you either include a library that can do XML writing, or switch to a simpler format such as CSV or JSON (I personally use rapidJSON to export to a JSON format, but that may not work for you). You could also try to use OMNeT++'s statistics framework to export data, but it isn't really designed for arbitrary output, such as message logs.



Related Topics



Leave a reply



Submit