Skip to content

Commit

Permalink
#207 ns for attrs
Browse files Browse the repository at this point in the history
  • Loading branch information
yegor256 committed Dec 2, 2024
1 parent da995bb commit acdeddf
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/main/java/org/xembly/AttrDirective.java
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,13 @@ public Directive.Cursor exec(final Node dom,
final Directive.Cursor cursor, final Directive.Stack stack) {
final String key = this.name.raw();
final String val = this.value.raw();
final String[] parts = key.split(" ");
for (final Node node : cursor) {
Element.class.cast(node).setAttribute(key, val);
if (parts.length == 2) {
Element.class.cast(node).setAttributeNS(parts[1], parts[0], val);
} else {
Element.class.cast(node).setAttribute(key, val);
}
}
return cursor;
}
Expand Down
4 changes: 4 additions & 0 deletions src/main/java/org/xembly/Directives.java
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,10 @@ public Directives remove() {
/**
* Set attribute.
*
* <p>If it's necessary to add an attribute with a namespace, append
* the namespace to the name of the attribute, separating them
* with a space.</p>
*
* <p>If a value provided contains illegal XML characters, a runtime
* exception will be thrown. To avoid this, it is recommended to use
* {@link Xembler#escape(String)}.
Expand Down
17 changes: 17 additions & 0 deletions src/test/java/org/xembly/AttrDirectiveTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,12 @@
package org.xembly;

import com.jcabi.matchers.XhtmlMatchers;
import com.jcabi.xml.XMLDocument;
import java.util.Collections;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.lang3.StringUtils;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
Expand Down Expand Up @@ -100,4 +102,19 @@ void addsCaseSensitiveAttributesDirectly() throws Exception {
XhtmlMatchers.hasXPath("/f[@Price='\u20ac50']")
);
}

@Test
void addAttributeWithNamespace() {
MatcherAssert.assertThat(
new XMLDocument(
new Xembler(
new Directives().add("boom").attr(
"noNamespaceSchemaLocation http://www.w3.org/2001/XMLSchema-instance",
"foo.xsd"
)
).domQuietly()
).nodes("/boom/@xsi:noNamespaceSchemaLocation"),
Matchers.not(Matchers.emptyIterable())
);
}
}

0 comments on commit acdeddf

Please sign in to comment.