Untitled
unknown
plain_text
a year ago
1.8 kB
1
Indexable
Never
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import java.io.File; import java.io.IOException; import java.util.Optional; public class XmlReader { public static void main(String[] args) { String filePath = "path/to/your/xml/file.xml"; String propertyName = "XMFG"; try { Optional<String> propertyValue = readXmlPropertyValue(filePath, propertyName); propertyValue.ifPresent(value -> System.out.println(propertyName + " value: " + value)); } catch (IOException e) { System.err.println("An error occurred while reading the XML file: " + e.getMessage()); } } private static Optional<String> readXmlPropertyValue(String filePath, String propertyName) throws IOException { ObjectMapper objectMapper = new XmlMapper(); JsonNode rootNode = objectMapper.readTree(new File(filePath)); return findPropertyValue(rootNode, propertyName); } private static Optional<String> findPropertyValue(JsonNode node, String propertyName) { if (node.isObject()) { ObjectNode objectNode = (ObjectNode) node; if (objectNode.has(propertyName)) { return Optional.ofNullable(objectNode.get(propertyName).asText()); } else { return objectNode.fieldNames().stream() .map(fieldName -> findPropertyValue(objectNode.get(fieldName), propertyName)) .filter(Optional::isPresent) .map(Optional::get) .findFirst(); } } return Optional.empty(); } }