When parsing XML files in Java, you sometimes need to obtain nodes that meet certain conditions.Code.
Import javax. XML. XPath. XPath; import javax. XML. XPath. xpathconstants; import javax. XML. XPath. xpathexpressionexception; import javax. XML. XPath. xpathfactory; import Org. eclipse. SWT. widgets. shell; import Org. eclipse. SWT. widgets. text; import Org. w3C. dom. element; string value = new string ("test"); XPath = xpathfactory. newinstance (). newxpath (); string expression = "// elementname [@ modulename = '" + value + "']"; element = NULL; try {element = (element) XPath. evaluate (expression, document, xpathconstants. node);} catch (xpathexpressionexception e) {e. printstacktrace ();}
AboveProgramIn all elementname nodes,FindThe node whose attribute modulename is value.
If you need to findAllChange xpathconstants. node to xpathconstants. nodeset. In this case, the return value type is nodelist. After forced type conversion, you can perform further operations on all nodes that meet the conditions.