Find tag in xml java

Java XPath – Check if Node or Attribute Exists?

Java example to check if a node exists in given XML content or check if an attribute exists in XML using XPath.

1. How to check if an XML node or attribute exists?

To verify if a node or tag exists in an XML document, we can use one of two approaches:

1. Select the nodes using XPath expression and count the matches.

#Expression for finding all employee ids where id is an attribute //employees/employee/@id 

2. Use count() function is the expression to directly access the count of matching nodes. If count is greater than zero, then the node exists, else not.

#Directly count all the ids count(//employees/employee/@id)

For demo purposes, we are using the following XML file.

   Lokesh Gupta 101 IT   Brian Schultz 102 HR   

The following code uses both of the above-discussed techniques to find if a node or attribute exists. To understand the code in-depth, read the XPath tutorial.

import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; public class CheckIfNodeExists < public static void main(String[] args) throws Exception < DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse("employees.xml"); XPathFactory xpathfactory = XPathFactory.newInstance(); XPath xpath = xpathfactory.newXPath(); //1 XPathExpression expr = xpath.compile("//employees/employee/@id"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; if(nodes.getLength() >0) < System.out.println("Attribute or Node Exists"); >else < System.out.println("Attribute or Node Does Not Exist"); >//2 expr = xpath.compile("count(//employees/employee/@id)"); result = expr.evaluate(doc, XPathConstants.NUMBER); Double count = (Double) result; if(count > 0) < System.out.println("Attribute or Node Exists"); >else < System.out.println("Attribute or Node Does Not Exist"); >> >
Attribute or Node Exists Attribute or Node Exists

Источник

Читайте также:  Attach javascript to html file

Пример работы с XPath в Java. Поиск в XML и выборка данных

Пример работы с XPath в Java. Поиск в XML и выборка данных

В этой статье мы рассмотрим пример работы с XPath в Java, а именно научимся находить нужную нам информацию с помощью XPath выражений и делать выборку из XML документа по различным условиям.

Кратко сведения про XPath

XPath предоставляет специальный синтаксис для поиска и выборки данных в XML документе. Используя XPath выражения, мы можем произвести выборку по условию, найти узлы или точное значение из любой части XML-документа.

XPath является частью платформы Java SE и находится в пакете javax.xml.xpath , поэтому никаких дополнительных зависимостей подключать не нужно — все работает прямо из коробки.

Для создания выражения для выборки по условию используется класс XPathExpression , который создается с помощью фабричных методов XPathFactory.newInstance() и вызова xpathFactory.newXPath() . Результат выборки должен быть представлен одним из 5 возможных типов:

  • XPathConstants.STRING
  • XPathConstants.NUMBER
  • XPathConstants.BOOLEAN
  • XPathConstants.NODE
  • XPathConstants.NODESET

Пример работы с XPath в Java

Перед нами стоит задача получить информацию из XML файла разработчиков по следующим критериям:

  1. Узнать имена разработчиков, возраст которых меньше заданного в условии.
  2. Получить имена всех мидлов.
  3. Получить имя по известному id.

У нас есть XML документ с таким содержимым:

Источник

Java XPath – Find XML Nodes by Attribute Value

This Java tutorial demonstrates how to get matching nodes for an attribute value in an XML document using XPath.

First look at the XML file which we will read and then fetch information from it, using xpath queries.

   Lokesh Gupta 101 IT   Brian Schultz 102 HR   

Now see a few examples of how to build an xpath expression.

Description XPath
Get all employee ids /employees/employee/@id
Get all employees with id equals to 1 /employees/employee[@id = 1]
Get all employees with id greater than 1 /employees/employee[@id > 1]
Get all employees with id contains 1 /employees/employee[contains(@id,’1′)]
Get department of all employees with id contains 1 /employees/employee[contains(@id,’1′)]/department
Get first name whose id contains ‘1’ in any child nodes descendant-or-self::*[contains(@id,’1′)]/firstName/text()

2. Using XPath to Find Nodes for Specified Attribute Value

Let’s look at the code which has been used to evaluate the above xpath expressions to select nodes having certain attribute values.

To evaluate xpath in java, we need to follow these steps:

  • Read XML file into org.w3c.dom.Document .
  • Create XPathFactory with its newInstance() static method.
  • Get XPath instance from XPathFactory . This object provides access to the xpath evaluation environment and expressions.
  • Create an xpath expression string. Convert xpath string to XPathExpression object using xpath.compile() method.
  • Evaluate xpath against the document instance created in the first step. It will return a list of DOM nodes from the document.
  • Iterate nodes and get the test values using getNodeValue() method.

The following code creates a DOM Node for an XML file.

An XPath expression is not thread-safe. It is the application’s responsibility to make sure that one XPathExpression object is not used from more than one thread at any given time, and while the evaluate method is invoked, applications may not recursively call the evaluate method.

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse("employees.xml");

Next, the following function takes the DOM model and XPath expression, and returns all values obtained from evaluating the expression.

private static List evaluateXPath(Document document, String xpathExpression) < XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); Listvalues = new ArrayList<>(); try < XPathExpression expr = xpath.compile(xpathExpression); NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) < //Customize the code to fetch the value based on the node type and hierarchy values.add(nodes.item(i).getNodeValue()); >> catch (XPathExpressionException e) < e.printStackTrace(); >return values; >

Now, we can test the expressions we discussed in the first section. Find id attribute value for all employees.

String xpathExpression = "/employees/employee/@id"; evaluateXPath(document, xpathExpression);

Drop me your questions related to how to find xml element with attribute value using xpath.

Источник

Оцените статью