Java program for XML file Operations (cont.)

Source: Internet
Author: User
Tags array int size trim
xml| program/**
* Helper method, looking for a specified element
*
* @param name element names, formatted as x.y.z
* @return element is returned if found, otherwise null
*/
Public Element findonly (String name)
{
Name of the exploded element
string[] propname = parsepropertyname (name);
Element element = This.doc.getRootElement ();
Traversal search for matching elements
for (int i = 0; i < propname.length; i++)
{
element = Element.getchild (Propname[i]);
if (element = = NULL) return null;
}
We got it!
return element;
}
/**
* Saves the properties to disk as an XML document. A Temporary file is
* Used during the writing process for maximum safety.
*/
Public synchronized void SaveProperties () {
OutputStream out = null;
Boolean error = FALSE;
Write data out to a temporary file.
File tempfile = null;
try {
Tempfile = new File (File.getparentfile (), file.getname () + ". tmp");
Use JDOM ' s xmloutputter to do the writing and formatting. The
File should always come out pretty-printed.
Increase this line to support Chinese Wyl 20021015
Xmloutputter outputter = new Xmloutputter ("", True, "GB2312");
out = new Bufferedoutputstream (new FileOutputStream (tempfile));
Increase this row so that the XML file has no blank lines. Wyl 20021030
Outputter.settextnormalize (TRUE);
Outputter.output (Doc, out);
}
catch (Exception e) {
E.printstacktrace ();
There were errors so abort replacing the old property file.
Error = TRUE;
}
finally {
try {out.close (); }
catch (Exception e) {
E.printstacktrace ();
Error = TRUE;
}
}
No errors occured, so we should being safe in replacing the old
if (!error) {
Delete the old file so we can replace it.
if (!file.delete ()) {
System.err.println ("Error deleting Property file:" +
File.getabsolutepath ());
Return
}
Rename the temp file. The Delete and rename won ' t is an
Automic operation, but we should be pretty safe in general.
At the very least, the temp file should remain in some form.
if (!tempfile.renameto (file)) {
System.err.println ("Error renaming temp file from" +
Tempfile.getabsolutepath () + "to" + File.getabsolutepath ());
}
}
}
/**
* Returns an array representation to the given CRM property. Crm
* Properties are always in the format "Prop.name.is.this" which would is
* Represented as an array of four Strings.
*
* @param name The name of the CRM property.
* @return An array representation of the given CRM property.
*/
Public string[] Parsepropertyname (String name) {
Figure out of the number of parts of the ' name ' (this becomes the size
of the resulting array).
int size = 1;
for (int i=0; i<name.length (); i++) {
if (Name.charat (i) = = '. ') {
size++;
}
}
string[] propname = new String[size];
Use a StringTokenizer to tokenize the property name.
StringTokenizer tokenizer = new StringTokenizer (name, ".");
int i = 0;
while (Tokenizer.hasmoretokens ()) {
Propname[i] = Tokenizer.nexttoken ();
i++;
}
return propname;
}
Private string[] Parseattributename (String name)
{
Figure out of the number of parts of the ' name ' (this becomes the size
of the resulting array).
if (name==null) return null;

int size = 1;
for (int i=0; i<name.length (); i++)
{
if (Name.charat (i) = = ' = ')
{
size++;
}
}
if (size!=2) return null;
string[] Attrname = new String[size];
Use a StringTokenizer to tokenize the property name.
StringTokenizer tokenizer = new StringTokenizer (name, "=");
for (int i=0;tokenizer.hasmoretokens (); i++)
Attrname[i] = Tokenizer.nexttoken ();
return attrname;
}
/**
* @param element element==null start from root
* @param attname attribute name
* @return attribute value of this element
* @author Qiuss
* @date 2001.11.08
*/

Public String getattribute (Element element,string attname)
{
if (attname==null) return null;
The Search for this property is traversing down the XML heirarchy.
if (element==null) element = Doc.getrootelement ();
Attribute att;
String value;
if ((Att=element.getattribute (AttName))!=null)
Value = Att.getvalue ();
Else
return null;
if ("". Equals (value))
{
return null;
}
Else
{
return Value.trim ();
}
}
Qiuss 2001.11.08

public string getattribute (String elename,string attname)
{
string[] propname = Parsepropertyname (elename);
The Search for this property is traversing down the XML heirarchy.
Element element = Doc.getrootelement ();
for (int i = 0; i < propname.length; i++)
{
element = Element.getchild (Propname[i]);
if (element = = null)
{
This node doesn ' t match this Part's property name which
Indicates this property doesn ' t exist to return NULL.
return null;
}
}
At this point, we found a matching property, so return of its value.
Empty strings are returned as null.
String value = "";
try{
Value= Element.getattribute (AttName). GetValue ();
}
catch (Exception e)
{
Value = "";
}
if ("". Equals (value))
{
Return "";
}
Else
{
return Value.trim ();
}
}
public static void Main (string[] args)
{
Xmlproperty xmltree = new Xmlproperty ("D:/project/bicp-ivr/crm_config.xml");
Changes the attribute value of an element if it exists
Xmltree.setproperty ("System.connection.username2", "type", "Chinese Test");
Does not exist create a new element
Xmltree.setproperty ("system.connection. User name", "ECOM4");
Xmltree.setproperty ("system.connection. User name", "type", "Chinese Test 2222");
Delete an XML
Xmltree.deleteproperty ("system.connection.username2");
String db_url= xmltree.getproperty ("System.connection.db_url");
String db_url_id= "";
Db_url_id=xmltree.getattribute ("System.information.db_url", "remark");
Debug.println ("db_url=" +db_url);
Debug.println ("db_url_id=" +db_url_id);
String names[] = xmltree.parsepropertyname ("Style.body");
for (int i=0;i<names.length;i++)
//        {
Debug.println ("i=" +i+ "" +names[i]);
//        }
String child[] = xmltree.getchildrenproperties ("Style.body");
for (int j=0;j<child.length;j++)
{
Debug.println ("j=" +j+ "" +child[j]);
String child2[]= xmltree.getchildrenproperties ("System.tracelog." +CHILD[J]);
for (int k=0;k<child2.length;k++)
{
Debug.println ("k=" +k+ "" +child2[k]);
}
}

System.out.println ("Hello world!");

}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.