Skip to content

Commit 2518355

Browse files
committed
Support for removing nodes based on a predicate
1 parent ddc139d commit 2518355

File tree

4 files changed

+34
-18
lines changed

4 files changed

+34
-18
lines changed

.travis.yml

-16
This file was deleted.

build.gradle

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ apply plugin: "java"
1111

1212

1313
group = 'com.developerb.nmxmlp'
14-
version = '1.6.1'
14+
version = '1.6.2'
1515

1616
compileJava {
1717
sourceCompatibility = 1.8

src/main/java/com/developerb/nmxmlp/NX.java

+25-1
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,8 @@ public interface Cursor {
232232

233233
void remove() throws Ex;
234234

235+
void removeChildren(Predicate<Cursor> predicate) throws Ex;
236+
235237
String text();
236238

237239
String describePath();
@@ -272,7 +274,7 @@ public interface Cursor {
272274
<R> void update(R payload, Inserter<R> inserter) throws Ex;
273275

274276
/**
275-
* @param attributeName
277+
* @param attributeName Name of the attribute
276278
* @return True if the node has an attribute with the given name
277279
*/
278280
boolean hasAttr(String attributeName);
@@ -477,6 +479,9 @@ public <R> void update(R payload, Inserter<R> inserter) {
477479
public void remove() throws Ex {
478480
}
479481

482+
@Override
483+
public void removeChildren(Predicate<Cursor> predicate) throws Ex { }
484+
480485
@Override
481486
public boolean hasAttr(String attributeName) {
482487
return false;
@@ -670,6 +675,25 @@ public void remove() throws Ex {
670675
node.getParentNode().removeChild(node);
671676
}
672677

678+
@Override
679+
public void removeChildren(Predicate<Cursor> predicate) throws Ex {
680+
NodeList childNodes = node.getChildNodes();
681+
List<Cursor> toBeRemoved = new ArrayList<>();
682+
683+
for (int i = 0; i < childNodes.getLength(); i++) {
684+
Node childNode = childNodes.item(i);
685+
Cursor cursor = new NodeCursor(document, ancestors, childNode, i);
686+
687+
if (predicate.test(cursor)) {
688+
toBeRemoved.add(cursor);
689+
}
690+
}
691+
692+
for (Cursor cursor : toBeRemoved) {
693+
cursor.remove();
694+
}
695+
}
696+
673697
@Override
674698
public <R> R extract(Class<R> type) throws Ex {
675699
final Extractor<R> extractor = extractorFor(type);

src/test/java/com/developerb/nmxmlp/RemoveNodeTest.java

+8
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,12 @@ void removingNodeFromEmptyCursorDoesNothing() {
2424
cursor.toOptional("no-such-node").remove();
2525
}
2626

27+
@Test
28+
void removeUsingPredicate() {
29+
NX.Cursor cursor = parse("<root><aa>a</aa><ab>ab</ab><ba>ba</ba></root>");
30+
cursor.removeChildren((c) -> c.name().startsWith("a"));
31+
32+
assertEquals("<root><ba>ba</ba></root>", cursor.dumpXml(UTF_8, NX.Feature.DUMP_WITHOUT_XML_DECLARATION));
33+
}
34+
2735
}

0 commit comments

Comments
 (0)