Use XPath to add, find, delete, and move nodes up and down __java

Source: Internet
Author: User
Tags xpath

Recently, in the project development of a test tool, SWT's tree controls need to be built to organize test cases, and SWT itself provides tree controls to develop trees, all I have to do is organize the data into an XML file in accordance with the business logic, and construct the tree by parsing XML, The XML code is as follows:

<?xml version= "1.0" encoding= "GB2312" standalone= "no"?>
<configs>
<project name= "Test 1" >
	<report name= "test Report"/>
	<testsuite name= "newSuite1" >
	   <testcase name= "NewCase1" >
		<teststep>newStep7</teststep>		<teststep>newStep00</teststep>		< teststep>newstep1</teststep>		<teststep>newStep2</teststep>	   </ testcase>	   <testcase name= "NewCase5" >		<teststep>copy1tonewstep00</ teststep></testcase>	</testsuite>
</project>
<project name= "Test 2" >	<report name= "test Report"/>
</project>
</configs>

1, creating nodes in XML

try {documentbuilderfactory dbf = documentbuilderfactory.newinstance ();  
    Documentbuilder db = Dbf.newdocumentbuilder (); 
    Document document = Db.parse (FilePath); report.html Directory File Reportfile = new file (Stringcontent.tester_base_path + "\" + projectname + "\" + "report.html")
    ;
    NodeList rootlist = document.getElementsByTagName ("configs");
         for (int i = 0; i < rootlist.getlength (); i++) {Node Prjnode = Rootlist.item (i);
         Element PROJECT_ELMT = document.createelement ("project");
         Attr name_s = Document.createattribute ("name");
         Name_s.setvalue (ProjectName);
         Project_elmt.setattributenode (name_s);
         Prjnode.appendchild (PROJECT_ELMT);
         The report.html is hung in the engineering catalogue Element REPORT_ELMT = document.createelement ("the");
         Attr Name_r = Document.createattribute ("name");
         Name_r.setvalue (Reportfile.getname ());
         Name_r.setvalue ("test Report"); Report_elmt.setattributenode (nAme_r);
    Project_elmt.appendchild (REPORT_ELMT);
             
 SaveXML (document);

2, delete the node

First, you find the node and then delete it. The code is as follows

public static void Deleteteststep (String prjnm, String suitenm,string testylnm,string stepnm) {try{
	Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();
	Documentbuilder db = Factory.newdocumentbuilder ();
	Document xmldoc = db.parse (new File (FilePath));
	Element root = Xmldoc.getdocumentelement (); Select the Step node if ((prjnm!= null && prjnm!= "") && (suitenm!= null && suitenm!= "") && ( TESTYLNM!= null && testylnm!= "") && (stepnm!= null && stepnm!= "")) {nodelist nodes = Sel
           Ectnodes ("/configs/project[@name = '" +prjnm+ "]" + "/testsuite/testcase/teststep", root); for (int i = 0;i<nodes.getlength (); i++) {if (Nodes.item (i). Gettextcontent (). Equals (STEPNM)) {Nodes.item (i). Getpare
		Ntnode (). RemoveChild (Nodes.item (i));
	} savexml (xmldoc);
	}else{System.out.println ("node is not exists");
	catch (Exception e) {e.printstacktrace (); }
    }
}

3. Move nodes up and down

One is to move the leaf node, one is to move the parent node including its child nodes. Moving a leaf node needs to find its sibling node and Exchange node content, which is simpler. When the parent node and its leaf node are moved, the sibling node of the parent node is exchanged. The child nodes under the parent node are then copied to a temporary variable, and the child nodes are deleted, the child nodes under its sibling node are assigned to the parent node, and the child nodes saved in the temporary variable are assigned to the sibling node of the parent node.

1) Get the sibling node of the selected node----move the leaf node

/** * Gets the sibling node of the selected node--step * @param nodelist * @param node * @return * * private static void getnextsibling (Nodelis
   	  T nodelist,string Nodevalue,int flag) {Boolean isloop = true;
	  String tmp = "";
	  Node nextSibling = null;
		if (flag = = 2) {//step Move down for (int i = 0; i < nodelist.getlength (); i++) {Node Curnode = Nodelist.item (i); if (curnode.getnodetype () = = Node.element_node) {if (Nodelist.item (i). Gettextcontent (). Equals (NodeValue)) {WH
		        Ile (Isloop) {Node curnode_1 = Nodelist.item (i);  if (curno_1!= null&& curnode_1.getnextsibling ()!= null && curnode_1.getnextsibling (). Getnodetype ()
			= = Node.element_node) {nextSibling = Curnode_1.getnextsibling ();
			Swap step Content tmp = Nextsibling.gettextcontent (); curnode.settextcontent (TMP);
			Nextsibling.settextcontent (NodeValue);
		    Isloop = false;
		    if (I < nodelist.getlength ()) {i++;
		    else {isloop = false; }} BreaK }else{//step up for (int i = Nodelist.getlength ()-1; I >= 0; i--) {Node Curnode = Nodel
		Ist.item (i); if (curnode.getnodetype () = = Node.element_node) {if (Nodelist.item (i). Gettextcontent (). Equals (NodeValue)) {Whil
			E (isloop) {Node curnode_1 = Nodelist.item (i); if (curnode_1!= null && curnode_1.getprevioussibling ()!= null && curnode_1.getprevioussibling ()
			   . Getnodetype () = = Node.element_node) {nextSibling = Curnode_1.getprevioussibling ();
			   Swap step Content tmp = Nextsibling.gettextcontent ();
			   Curnode.settextcontent (TMP);
			   Nextsibling.settextcontent (NodeValue);
			Isloop = False} if (I >= 0) {i--;
			else {isloop = false;
 		}} break; }
	    }
	}
    }
}

4. Generate a temporary node to hold the child nodes under the parent node to be moved

Element node_tmp = xmldoc.createelement ("TestCase");	
Create a temporary node to save the step
node_tmp.setattribute ("name", "Test");
Copy the step below to the new node for
(int i = 0; i < stepnode1_list.getlength (); i++) {
   Element n1 = xmldoc.createelement ("Te Ststep "); 
   N1.settextcontent (Stepnode1_list.item (i). Gettextcontent ());
   Node_tmp.appendchild (n1);
}
Delete all step for
(int i = 0; i < stepnode1_list.getlength (); i++) {
   Stepnode1_list.item (i) under Curcase. Getparentnode (). RemoveChild (Stepnode1_list.item (i));
}

The rest of the work is to exchange two child nodes under the parent node, here is not to elaborate. The following two important methods are needed to find, remove, and rename all of the nodes listed above, including those not mentioned here:

5. Using XPath to find nodes, node collections

	/**
	 * Lookup node and return the first eligible node
	 * @param Express
	 * @param source
	 * @return
	/Public Staticnode selectSingleNode (String Express, Object source) {Node result = null;
		Xpathfactory xpathfactory = Xpathfactory.newinstance (); XPath XPath = Xpathfactory.newxpath ();
		try {result
		   = (Node) xpath.evaluate (Express, Source,  Xpathconstants.node);
		} catch ( Xpathexpressionexception e) {
			e.printstacktrace ();
		}
		return result;
	}

	/**
	 *  Lookup node that returns the set of nodes that meet the criteria.
	 * @param Express
	 * @param source
	 * @return
	/public static nodelist selectnodes (String Express, Object Source {
		nodelist result = null;
		Xpathfactory xpathfactory = Xpathfactory.newinstance ();
		XPath XPath = Xpathfactory.newxpath ();
		try {result
			= (nodelist) xpath.evaluate (Express, Source, Xpathconstants.nodeset);
		} catch ( Xpathexpressionexception e) {
			e.printstacktrace ();
		}
		return result;
	}


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.