Java + uses XPath to obtain nodes that meet specific conditions in the XML file

Source: Internet
Author: User

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.

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.