DOM
package name.panitz.util.xml;
import java.util.Set;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class DOM implements DOMUtil{
public long height(Node n){
long result = 0;
NodeList ns = n.getChildNodes();
for (int i = 0;i<ns.getLength() ;i++){
result = Math.max(result,height(ns.item(i)));
}
return result + 1;
}
public long height2(Node n){
return new NodeListSpliterator(n.getChildNodes())
.parallelStream()
.reduce(0L
, (r, child) -> Math.max(r, height2(child))
, Math::max)
+1;
}
public void collectText(Node n, StringBuffer result){
if (Node.TEXT_NODE == n.getNodeType())
result.append(n.getNodeValue());
NodeList ns = n.getChildNodes();
for (int i = 0;i<ns.getLength() ;i++){
collectText(ns.item(i),result);
}
}
public void collectText2(Node n, StringBuffer result){
if (Node.TEXT_NODE == n.getNodeType())
result.append(n.getNodeValue());
new NodeListSpliterator(n.getChildNodes())
.stream()
.forEach(child->collectText2(child,result));
}
@Override
public boolean containsTag(Node n, String tagname) {
if (n.getNodeType()==Node.ELEMENT_NODE
&& n.getNodeName().equals(tagname)){
return true;
}
NodeList ns = n.getChildNodes();
for (int i = 0;i<ns.getLength() ;i++){
if (containsTag(ns.item(i),tagname)) return true;
}
return false;
}
public boolean containsTag3(Node n, String tagname) {
return (n.getNodeType()==Node.ELEMENT_NODE
&& n.getNodeName().equals(tagname))
|| new NodeListSpliterator(n.getChildNodes())
.parallelStream()
.reduce(false
,( r, child)->r||containsTag3(child, tagname)
,(x,y)-> x|| y);
}
@Override
public boolean containsTag2(Node n, String tagname) {
return (n.getNodeType()==Node.ELEMENT_NODE
&& n.getNodeName().equals(tagname))
|| new NodeListSpliterator(n.getChildNodes())
.parallelStream()
.anyMatch(x->containsTag2(x,tagname));
}
@Override
public void collectTagnames(Node n, Set<String> result) {
if (n.getNodeType()==Node.ELEMENT_NODE)result.add(n.getNodeName());
NodeList ns = n.getChildNodes();
for (int i = 0;i<ns.getLength() ;i++)
collectTagnames(ns.item(i), result);
}
@Override
public void collectTagnames2(Node n, Set<String> result) {
if (n.getNodeType()==Node.ELEMENT_NODE)result.add(n.getNodeName());
new NodeListSpliterator(n.getChildNodes())
.stream()
.forEach(child->collectTagnames2(child,result));
}
@Override
public long getMaxWIDTHAttributeValue(Node n) {
long result = 0;
NamedNodeMap attributes = n.getAttributes();
if (attributes!=null){
Node a = attributes.getNamedItem("width");
if(a != null
&& !a.getNodeValue().isEmpty()
&& a.getNodeValue()
.chars()
.mapToObj(x->(new Boolean(Character.isDigit(x))))
.reduce(true,(x,y)->x&&y,(x,y)->x&&y)){
result = Math.max(result, new Long(a.getNodeValue()));
}
}
NodeList ns = n.getChildNodes();
for (int i = 0;i<ns.getLength() ;i++){
result = Math.max(getMaxWIDTHAttributeValue(ns.item(i)),result);
}
return result;
}
}