Best Cerberus-source code snippet using org.cerberus.util.XmlUtil.IterableNodeList
Source:XmlUtil.java
...71 * An {@link Iterable} {@link NodeList}72 *73 * @author abourdon74 */75 public static final class IterableNodeList implements NodeList, Iterable<Node> {76 /**77 * The delegate {@link NodeList} to iterate on it78 */79 private NodeList delegate;80 public IterableNodeList(NodeList delegate) {81 this.delegate = delegate;82 }83 @Override84 public int getLength() {85 return delegate.getLength();86 }87 @Override88 public Node item(int index) {89 return delegate.item(index);90 }91 @Override92 public Iterator<Node> iterator() {93 return new Iterator<Node>() {94 /**95 * The current index for this iterator96 */97 private int currentIndex = 0;98 @Override99 public boolean hasNext() {100 return currentIndex < getLength();101 }102 @Override103 public Node next() {104 return item(currentIndex++);105 }106 @Override107 public void remove() {108 throw new IllegalStateException("Unable to remove a node from the nested list");109 }110 };111 }112 }113 /**114 * A universal namespace cache to use when parsing XML files against XPath115 *116 * @author abourdon117 * @see <a href="https://www.ibm.com/developerworks/library/x-nmspccontext/#N10158">...</a>118 */119 @SuppressWarnings("unchecked")120 public static final class UniversalNamespaceCache implements NamespaceContext {121 /**122 * The associated {@link Logger} to this class123 */124 private static final Logger LOG = LogManager.getLogger(UniversalNamespaceCache.class);125 public static final boolean DEFAULT_TOP_LEVEL_ONLY = false;126 /**127 * The associated maps between prefixes and URIs128 */129 private Map<String, String> prefix2Uri = new HashMap<>();130 private Map<String, String> uri2Prefix = new HashMap<>();131 public UniversalNamespaceCache(Document document) {132 this(document, DEFAULT_TOP_LEVEL_ONLY);133 }134 /**135 * This constructor parses the document and stores all namespaces it can136 * find. If toplevelOnly is <code>true</code>, only namespaces in the137 * root are used.138 *139 * @param document source document140 * @param toplevelOnly restriction of the search to enhance performance141 */142 public UniversalNamespaceCache(Document document, boolean toplevelOnly) {143 examineNode(document.getFirstChild(), toplevelOnly);144 if (LOG.isDebugEnabled()) {145 LOG.debug("Hereunder list of found namespaces (prefix, uri):");146 for (Map.Entry<String, String> items : prefix2Uri.entrySet()) {147 LOG.debug("{}, {}", items.getKey(), items.getValue());148 }149 }150 }151 /**152 * A single node is read, the namespace attributes are extracted and153 * stored.154 *155 * @param node to examine156 * @param attributesOnly if <code>true</code> no recursion happens157 */158 private void examineNode(Node node, boolean attributesOnly) {159 if (node == null) {160 LOG.warn("Unable to examine null node");161 return;162 }163 NamedNodeMap attributes = node.getAttributes();164 for (int i = 0; i < attributes.getLength(); i++) {165 Node attribute = attributes.item(i);166 storeAttribute((Attr) attribute);167 }168 if (!attributesOnly) {169 for (Node child : new IterableNodeList(node.getChildNodes())) {170 if (child.getNodeType() == Node.ELEMENT_NODE) {171 examineNode(child, false);172 }173 }174 }175 }176 /**177 * This method looks at an attribute and stores it, if it is a namespace178 * attribute.179 *180 * @param attribute to examine181 */182 private void storeAttribute(Attr attribute) {183 if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attribute.getNamespaceURI())) {184 putInCache(XMLConstants.XMLNS_ATTRIBUTE.equals(attribute.getNodeName()) ? XMLConstants.DEFAULT_NS_PREFIX : attribute.getLocalName(), attribute.getNodeValue());185 }186 }187 /**188 * Put the given prefix and URI in cache189 *190 * @param prefix to put in cache191 * @param uri to put in cache192 */193 private void putInCache(String prefix, String uri) {194 prefix2Uri.put(prefix, uri);195 uri2Prefix.put(uri, prefix);196 }197 /**198 * This method is called by XPath. It returns the namespace URI199 * associated to the given prefix.200 *201 * @param prefix to search for202 * @return uri203 */204 @Override205 public String getNamespaceURI(String prefix) {206 return prefix2Uri.get(prefix);207 }208 /**209 * This method is not needed in this context, but can be implemented in210 * a similar way.211 */212 @Override213 public String getPrefix(String namespaceURI) {214 return uri2Prefix.get(namespaceURI);215 }216 @Override217 @SuppressWarnings("rawtypes")218 public Iterator getPrefixes(String namespaceURI) {219 return null;220 }221 }222 /**223 * Returns a new {@link Document} instance from the default224 * {@link DocumentBuilder}225 *226 * @return a new {@link Document} instance from the default227 * {@link DocumentBuilder}228 * @throws XmlUtilException if an error occurred229 */230 public static Document newDocument() throws XmlUtilException {231 try {232 DocumentBuilderFactory resultDocFactory = DocumentBuilderFactory.newInstance();233 DocumentBuilder resultDocBuilder = resultDocFactory.newDocumentBuilder();234 return resultDocBuilder.newDocument();235 } catch (ParserConfigurationException e) {236 throw new XmlUtilException(e);237 }238 }239 /**240 * Returns a {@link String} representation of the {@link Node} given in241 * argument242 *243 * @param node the {@link Node} from which create the {@link String}244 * representation245 * @return the {@link String} representation of the {@link Node} given in246 * argument247 * @throws XmlUtilException if {@link Node} cannot be represented as a248 * {@link String}249 */250 public static String toString(Node node) throws XmlUtilException {251 if (node == null) {252 throw new XmlUtilException("Cannot parse a null node");253 }254 try {255 StreamResult xmlOutput = new StreamResult(new StringWriter());256 Transformer transformer = TransformerFactory.newInstance().newTransformer();257 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");258 transformer.transform(new DOMSource(node), xmlOutput);259 return xmlOutput.getWriter().toString();260 } catch (TransformerFactoryConfigurationError | TransformerException e) {261 throw new XmlUtilException(e);262 }263 }264 /**265 * Returns a {@link Document} representation of the {@link String} given in266 * argument267 *268 * @param xml the {@link String} from which create the {@link Document}269 * representation270 * @param namespaceAwareness if namespaces have to be taking into account271 * during parsing272 * @return the {@link Document} representation of the {@link String} given273 * in argument274 * @throws XmlUtilException if {@link String} cannot be represented as a275 * {@link Document}276 */277 public static Document fromString(String xml, boolean namespaceAwareness) throws XmlUtilException {278 if (xml == null) {279 throw new XmlUtilException("Cannot parse a null XML file");280 }281 try {282 return newDocumentBuilder(namespaceAwareness, true).parse(new InputSource(new StringReader(xml)));283 } catch (SAXException | IOException | ParserConfigurationException e) {284 throw new XmlUtilException(e);285 }286 }287 /**288 * The {@link #fromString(String, boolean)} version by using the289 * {@link #DEFAULT_NAMESPACE_AWARENESS} value290 */291 public static Document fromString(String xml) throws XmlUtilException {292 return fromString(xml, DEFAULT_NAMESPACE_AWARENESS);293 }294 /**295 * Returns a {@link Document} representation of the {@link URL} given in296 * argument297 *298 * @param url the {@link URL} from which create the {@link Document}299 * representation300 * @param namespaceAwareness if namespaces have to be taking into account301 * during parsing302 * @return the {@link Document} representation of the {@link URL} given in303 * argument304 * @throws XmlUtilException if {@link URL} cannot be represented as a305 * {@link Document}306 */307 public static Document fromURL(URL url, boolean namespaceAwareness) throws XmlUtilException {308 if (url == null) {309 throw new XmlUtilException("Cannot parse a null URL");310 }311 try {312 return newDocumentBuilder(namespaceAwareness, true).parse(new BufferedInputStream(url.openStream()));313 } catch (SAXException | IOException | ParserConfigurationException e) {314 throw new XmlUtilException(e);315 }316 }317 /**318 * The {@link #fromURL(URL, boolean)} version by using the319 * {@link #DEFAULT_NAMESPACE_AWARENESS} value320 *321 * @see #fromURL(URL, boolean)322 */323 public static Document fromURL(URL url) throws XmlUtilException {324 return fromURL(url, DEFAULT_NAMESPACE_AWARENESS);325 }326 /**327 * Evaluates the given xpath against the given document and produces new328 * document which satisfy the xpath expression.329 *330 * @param document the document to search against the given xpath331 * @param xpath the xpath expression332 * @return a list of new document which gather all results which satisfy the333 * xpath expression against the given document.334 * @throws XmlUtilException if an error occurred335 */336 public static NodeList evaluate(Document document, String xpath) throws XmlUtilException {337 if (document == null || xpath == null) {338 throw new XmlUtilException("Unable to evaluate null document or xpath");339 }340 XPathFactory xpathFactory = XPathFactory.newInstance();341 XPath xpathObject = xpathFactory.newXPath();342 xpathObject.setNamespaceContext(new UniversalNamespaceCache(document));343 NodeList nodeList = null;344 try {345 XPathExpression expr = xpathObject.compile(xpath);346 nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET);347 } catch (XPathExpressionException xpee) {348 throw new XmlUtilException(xpee);349 }350 if (nodeList == null) {351 throw new XmlUtilException("Evaluation caused a null result");352 }353 return nodeList;354 }355 /**356 * Evaluates the given xpath against the given document and produces string357 * which satisfy the xpath expression.358 *359 * @param document the document to search against the given xpath360 * @param xpath the xpath expression361 * @return a string which satisfy the xpath expression against the given362 * document.363 * @throws XmlUtilException if an error occurred364 */365 public static String evaluateString(Document document, String xpath) throws XmlUtilException {366 if (document == null || xpath == null) {367 throw new XmlUtilException("Unable to evaluate null document or xpath");368 }369 XPathFactory xpathFactory = XPathFactory.newInstance();370 XPath xpathObject = xpathFactory.newXPath();371 xpathObject.setNamespaceContext(new UniversalNamespaceCache(document));372 String result = null;373 try {374 XPathExpression expr = xpathObject.compile(xpath);375 result = (String) expr.evaluate(document, XPathConstants.STRING);376 } catch (XPathExpressionException xpee) {377 throw new XmlUtilException(xpee);378 }379 if (result == null) {380 throw new XmlUtilException("Evaluation caused a null result");381 }382 return result;383 }384 public static Node evaluateNode(Document doc, String xpath) throws XmlUtilException {385 if (doc == null || xpath == null) {386 throw new XmlUtilException("Unable to evaluate null document or xpath");387 }388 XPathFactory xpathFactory = XPathFactory.newInstance();389 XPath xpathObject = xpathFactory.newXPath();390 xpathObject.setNamespaceContext(new UniversalNamespaceCache(doc));391 Node node = null;392 try {393 XPathExpression expr = xpathObject.compile(xpath);394 node = (Node) expr.evaluate(doc, XPathConstants.NODE);395 } catch (XPathExpressionException xpee) {396 throw new XmlUtilException(xpee);397 }398 if (node == null) {399 throw new XmlUtilException("Evaluation caused a null result");400 }401 return node;402 }403 /**404 * {@link String} version of the {@link #evaluate(Document, String)} method405 *406 * @see #evaluate(Document, String)407 */408 public static NodeList evaluate(String xml, String xpath) throws XmlUtilException {409 return evaluate(XmlUtil.fromString(xml), xpath);410 }411 /**412 * Returns a {@link Document} from the given {@link Node}413 *414 * @param node to transform to {@link Document}415 * @return a {@link Document} from the given {@link Node}416 * @throws XmlUtilException if an error occurs417 */418 public static Document fromNode(Node node) throws XmlUtilException {419 try {420 Document document = XmlUtil.newDocument();421 document.appendChild(document.adoptNode(node.cloneNode(true)));422 return document;423 } catch (DOMException e) {424 Log.warn("Unable to create document from node " + node, e);425 return null;426 }427 }428 /**429 * Returns a {@link Document} list from the given {@link NodeList}430 *431 * @param nodeList to parse432 * @return a {@link Document} list from the given {@link NodeList}433 * @throws XmlUtilException if an error occurs. For instance if434 * {@link NodeList} cannot be transforms as a {@link Document} list435 */436 public static List<Document> fromNodeList(NodeList nodeList) throws XmlUtilException {437 List<Document> result = new ArrayList<>();438 for (Node node : new IterableNodeList(nodeList)) {439 if (node == null) {440 throw new XmlUtilException("Unable to add null node");441 }442 result.add(fromNode(node));443 }444 return result;445 }446 public static boolean isXmlWellFormed(String xmlString) {447 DocumentBuilder dBuilder;448 try {449 dBuilder = newDocumentBuilder(true, true);450 dBuilder.parse(xmlString);451 } catch (ParserConfigurationException | SAXException e) {452 return false;...
Source:XmlUnitService.java
...150 }151152 try {153 NodeList candidates = XmlUtil.evaluate(lastSOAPResponse, xpath);154 for (Node candidate : new XmlUtil.IterableNodeList(candidates)) {155 boolean found = true;156 for (org.cerberus.service.xmlunit.Difference difference : Differences.fromString(getDifferencesFromXml(XmlUtil.toString(candidate), tree))) {157 if (!difference.getDiff().endsWith("/text()[1]")) {158 found = false;159 }160 }161162 if (found) {163 return true;164 }165 }166 } catch (XmlUtilException e) {167 LOG.warn("Unable to check similar tree", e);168 } catch (DifferencesException e) {
...
IterableNodeList
Using AI Code Generation
1import java.io.File;2import java.io.IOException;3import javax.xml.parsers.ParserConfigurationException;4import org.cerberus.util.XmlUtil;5import org.w3c.dom.Node;6import org.xml.sax.SAXException;7public class 3 {8 public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {9 File xmlFile = new File("D:\\xml\\test.xml");10 Node node = XmlUtil.getNodeByPath(xmlFile, "/root/test1/test2/test3");11 System.out.println(node.getNodeName());12 }13}14import java.io.File;15import java.io.IOException;16import javax.xml.parsers.ParserConfigurationException;17import org.cerberus.util.XmlUtil;18import org.w3c.dom.Node;19import org.xml.sax.SAXException;20public class 4 {21 public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {22 File xmlFile = new File("D:\\xml\\test.xml");23 IterableNodeList nodeList = XmlUtil.getNodeListByPath(xmlFile, "/root/test1/test2/test3");24 for (Node node : nodeList) {25 System.out.println(node.getNodeName());26 }27 }28}29import java.io.File;30import java.io.IOException;31import javax.xml.parsers.ParserConfigurationException;32import org.cerberus.util.XmlUtil;33import org.w3c.dom.Node;34import org.xml.sax.SAXException;35public class 5 {36 public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {37 File xmlFile = new File("D:\\xml\\test.xml");38 IterableNodeList nodeList = XmlUtil.getNodeListByPath(xmlFile, "/root/test1/test2/test3");39 for (Node node : nodeList) {40 System.out.println(node.getTextContent());41 }42 }43}44import java.io.File;45import java.io.IOException;46import javax.xml.parsers.ParserConfigurationException;47import org.cerberus.util.XmlUtil;48import org
IterableNodeList
Using AI Code Generation
1package org.cerberus.util;2import java.io.File;3import java.util.ArrayList;4import java.util.List;5import org.w3c.dom.Document;6import org.w3c.dom.Node;7import org.w3c.dom.NodeList;8public class TestXmlUtil {9 public static void main(String[] args) {10 File file = new File("C:\\Users\\dell\\Desktop\\test.xml");11 Document doc = XmlUtil.parseXmlFile(file);12 NodeList nodes;13 nodes = XmlUtil.iterableNodeList(doc.getElementsByTagName("test"));14 List<Node> list = new ArrayList<Node>();15 for (Node node : nodes) {16 list.add(node);17 }18 System.out.println(list.size());19 }20}21package org.cerberus.util;22import java.io.File;23import java.util.ArrayList;24import java.util.List;25import org.w3c.dom.Document;26import org.w3c.dom.Node;27import org.w3c.dom.NodeList;28public class TestXmlUtil {29 public static void main(String[] args) {30 File file = new File("C:\\Users\\dell\\Desktop\\test.xml");31 Document doc = XmlUtil.parseXmlFile(file);32 NodeList nodes;33 nodes = XmlUtil.iterableNodeList(doc.getElementsByTagName("test"));34 List<Node> list = new ArrayList<Node>();35 for (Node node : nodes) {36 list.add(node);37 }38 System.out.println(list.size());39 }40}41package org.cerberus.util;42import java.io.File;43import java.util.ArrayList;44import java.util.List;45import org.w3c.dom.Document;46import org.w3c.dom.Node;47import org.w3c.dom.NodeList;48public class TestXmlUtil {49 public static void main(String[] args) {50 File file = new File("C:\\Users\\dell\\Desktop\\test.xml");51 Document doc = XmlUtil.parseXmlFile(file);52 NodeList nodes;53 nodes = XmlUtil.iterableNodeList(doc.getElementsByTagName("test"));54 List<Node> list = new ArrayList<Node>();55 for (Node node : nodes) {56 list.add(node);57 }58 System.out.println(list.size());59 }60}
IterableNodeList
Using AI Code Generation
1import org.cerberus.util.XmlUtil;2import org.w3c.dom.NodeList;3public class 3 {4public static void main(String[] args) {5for (Node node : XmlUtil.iterableNodeList(nodelist)) {6System.out.println(node.getNodeName());7}8}9}
IterableNodeList
Using AI Code Generation
1import java.io.*;2import java.util.*;3import java.net.*;4import org.cerberus.util.*;5import org.w3c.dom.*;6import org.xml.sax.SAXException;7import javax.xml.parsers.*;8import javax.xml.parsers.DocumentBuilderFactory;9import javax.xml.parsers.DocumentBuilder;10import org.apache.xerces.parsers.DOMParser;11import org.xml.sax.InputSource;12import org.xml.sax.SAXException;13public class 3{14public static void main(String args[]) throws Exception{15DOMParser parser = new DOMParser();16parser.parse("3.xml");17Document document = parser.getDocument();18Element root = document.getDocumentElement();19NodeList nodeList = root.getChildNodes();20for (Node node : new IterableNodeList(nodeList)) {21String nodeName = node.getNodeName();22short nodeType = node.getNodeType();23String nodeValue = node.getNodeValue();24NamedNodeMap attributes = node.getAttributes();25int attributeCount = attributes.getLength();26for (int i = 0; i < attributeCount; i++) {27Node attribute = attributes.item(i);28String attributeName = attribute.getNodeName();29String attributeValue = attribute.getNodeValue();30System.out.println("Attribute Name: " + attributeName);31System.out.println("Attribute Value: " + attributeValue);32}33System.out.println("Node Name: " + nodeName);34System.out.println("Node Type: " + nodeType);35System.out.println("Node Value: " + nodeValue);36}37}38}
IterableNodeList
Using AI Code Generation
1import org.cerberus.util.*;2import org.w3c.dom.*;3import java.io.*;4public class 3 {5public static void main(String args[]) throws Exception {6File file = new File("test.xml");7Document doc = XmlUtil.getDocument(file);8Element root = doc.getDocumentElement();9IterableNodeList list = XmlUtil.getChildElements(root);10for (Node n : list) {11String name = n.getNodeName();12String value = XmlUtil.getElementValue((Element)n);13System.out.println(name + " = " + value);14}15}16}
IterableNodeList
Using AI Code Generation
1import java.io.File;2import java.io.IOException;3import java.util.Iterator;4import org.cerberus.util.XmlUtil;5import org.w3c.dom.Node;6public class 3 {7 public static void main(String[] args) throws IOException {8 XmlUtil xmlUtil = new XmlUtil();9 File f = new File("C:\\Users\\gaurav\\Desktop\\3.xml");10 Iterator<Node> it = xmlUtil.IterableNodeList(xmlUtil.parseXML(f));11 while(it.hasNext()){12 System.out.println(it.next().getTextContent());13 }14 }15}
IterableNodeList
Using AI Code Generation
1import java.io.File;2import java.util.Iterator;3import org.cerberus.util.XmlUtil;4import org.w3c.dom.Node;5import org.w3c.dom.NodeList;6public class 3 {7 public static void main(String[] args) throws Exception {8 if (args.length != 2) {9 System.err.println("Usage: java 3 <xml file> <xpath expression>");10 System.exit(1);11 }12 File file = new File(args[0]);13 String xpath = args[1];14 NodeList nl = XmlUtil.getNodes(file, xpath);15 Iterator<Node> iter = XmlUtil.iterableNodeList(nl).iterator();16 while (iter.hasNext()) {17 Node node = iter.next();18 System.out.println(node.getTextContent());19 }20 }21}
IterableNodeList
Using AI Code Generation
1import org.cerberus.util.XmlUtil;2import org.w3c.dom.Node;3import org.w3c.dom.NodeList;4import org.w3c.dom.Element;5public class 3 {6public static void main(String args[]) throws Exception {7for (Node node : list) {8System.out.println(node.getNodeName());9}10}11}12import org.cerberus.util.XmlUtil;13import org.w3c.dom.Node;14import org.w3c.dom.NodeList;15import org.w3c.dom.Element;16public class 4 {17public static void main(String args[]) throws Exception {18for (Node node : list) {19System.out.println(node.getNodeName());20}21}22}
IterableNodeList
Using AI Code Generation
1import java.util.List;2import java.util.Iterator;3import org.w3c.dom.NodeList;4import org.cerberus.util.XmlUtil;5public class 3 {6 public static void main(String[] args) {7 String xml = "<root><a>1</a><b>2</b><c>3</c></root>";8 NodeList nodeList = XmlUtil.parseXml(xml).getElementsByTagName("*");9 List list = XmlUtil.IterableNodeList(nodeList);10 for (Iterator i = list.iterator(); i.hasNext();) {11 System.out.println(i.next());12 }13 }14}15import java.util.List;16import java.util.Iterator;17import org.w3c.dom.NodeList;18import org.cerberus.util.XmlUtil;19public class 4 {20 public static void main(String[] args) {21 String xml = "<root><a>1</a><b>2</b><c>3</c></root>";22 NodeList nodeList = XmlUtil.parseXml(xml).getElementsByTagName("*");23 List list = XmlUtil.IterableNodeList(nodeList);24 for (Iterator i = list.iterator(); i.hasNext();) {25 System.out.println(i.next());26 }27 }28}29import java.util.List;30import java.util.Iterator;31import org.w3c.dom.NodeList;32import org.cerberus
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!