下面列出了org.w3c.dom.Element#appendChild ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void toXML(Document doc, Element parent) {
parent.setAttribute("type", "set");
Element el = doc.createElement(inScope.getName());
inScope.toXML(doc, el);
parent.appendChild(el);
el = doc.createElement(outOfScope.getName());
outOfScope.toXML(doc, el);
parent.appendChild(el);
el = doc.createElement(errors.getName());
errors.toXML(doc, el);
parent.appendChild(el);
}
/**
* Creates a new XML Schema element of the given local name
* and insert it as the first child of the given parent node.
*
* @return
* Newly create element.
*/
private Element insertXMLSchemaElement( Element parent, String localName ) {
// use the same prefix as the parent node to avoid modifying
// the namespace binding.
String qname = parent.getTagName();
int idx = qname.indexOf(':');
if(idx==-1) qname = localName;
else qname = qname.substring(0,idx+1)+localName;
Element child = parent.getOwnerDocument().createElementNS( WellKnownNamespace.XML_SCHEMA, qname );
NodeList children = parent.getChildNodes();
if( children.getLength()==0 )
parent.appendChild(child);
else
parent.insertBefore( child, children.item(0) );
return child;
}
@Test public void compareNodesDifferentNumberOfChildren() {
DOMDifferenceEngine d = new DOMDifferenceEngine();
DiffExpecter ex =
new DiffExpecter(ComparisonType.CHILD_NODELIST_LENGTH, 2);
d.addDifferenceListener(ex);
d.setComparisonController(ComparisonControllers.StopWhenDifferent);
Element e1 = doc.createElement("x");
Element e2 = doc.createElement("x");
assertEquals(wrap(ComparisonResult.EQUAL),
d.compareNodes(e1, new XPathContext(),
e2, new XPathContext()));
e1.appendChild(doc.createElement("x"));
assertEquals(wrapAndStop(ComparisonResult.DIFFERENT),
d.compareNodes(e1, new XPathContext(),
e2, new XPathContext()));
assertEquals(1, ex.invoked);
e2.appendChild(doc.createElement("x"));
assertEquals(wrap(ComparisonResult.EQUAL),
d.compareNodes(e1, new XPathContext(),
e2, new XPathContext()));
e2.appendChild(doc.createElement("x"));
assertEquals(wrapAndStop(ComparisonResult.DIFFERENT),
d.compareNodes(e1, new XPathContext(),
e2, new XPathContext()));
assertEquals(2, ex.invoked);
}
private static void extractAttributesToElements(Element root) {
NamedNodeMap attributeMap = root.getAttributes();
for (int i = 0; i < attributeMap.getLength(); i++) {
Attr attr = (Attr) attributeMap.item(i);
if (isNamespaceDef(attr)) {
continue;
}
Element attrElement = root.getOwnerDocument().createElement(attr.getName());
attrElement.setTextContent(attr.getValue());
root.appendChild(attrElement);
}
NodeList children = root.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
if (children.item(i) instanceof Element) {
extractAttributesToElements((Element) children.item(i));
}
}
}
void marshalPublicKey(Node parent, Document doc, String dsPrefix,
DOMCryptoContext context)
throws MarshalException
{
Element dsaElem = DOMUtils.createElement(doc, "DSAKeyValue",
XMLSignature.XMLNS,
dsPrefix);
// parameters J, Seed & PgenCounter are not included
Element pElem = DOMUtils.createElement(doc, "P", XMLSignature.XMLNS,
dsPrefix);
Element qElem = DOMUtils.createElement(doc, "Q", XMLSignature.XMLNS,
dsPrefix);
Element gElem = DOMUtils.createElement(doc, "G", XMLSignature.XMLNS,
dsPrefix);
Element yElem = DOMUtils.createElement(doc, "Y", XMLSignature.XMLNS,
dsPrefix);
p.marshal(pElem, dsPrefix, context);
q.marshal(qElem, dsPrefix, context);
g.marshal(gElem, dsPrefix, context);
y.marshal(yElem, dsPrefix, context);
dsaElem.appendChild(pElem);
dsaElem.appendChild(qElem);
dsaElem.appendChild(gElem);
dsaElem.appendChild(yElem);
parent.appendChild(dsaElem);
}
/** get as XML */
@Override
public Element getAsDOM(Document document) {
Element u = (Element) document.createElement("literal");
u.setAttribute("namespace", getNS().getFunctor());
if (negated()) {
u.setAttribute("negated", negated()+"");
}
u.appendChild(super.getAsDOM(document));
return u;
}
protected void addParametersToDocument( Document doc, Element parametersElement, Query query ) {
for ( Parameter param : query.getParameters() ) {
Element paramElement = doc.createElement( "parameter" ); //$NON-NLS-1$
paramElement.setAttribute( "name", param.getName() ); //$NON-NLS-1$
paramElement.setAttribute( "type", param.getType().toString() ); //$NON-NLS-1$
paramElement.setAttribute(
"defaultValue", param.getDefaultValue() == null ? "" : param.getDefaultValue().toString() ); //$NON-NLS-1$ //$NON-NLS-2$
parametersElement.appendChild( paramElement );
}
}
private void marshalSubjectName(String name, Node parent, Document doc,
String dsPrefix)
{
Element snElem = DOMUtils.createElement(doc, "X509SubjectName",
XMLSignature.XMLNS, dsPrefix);
snElem.appendChild(doc.createTextNode(name));
parent.appendChild(snElem);
}
/**
* Build arguments tags
*
* <argument type="service" id="foobar"/>
*/
private void appendArgumentXmlTags(@NotNull Document doc, @NotNull Element rootElement, @NotNull List<String> parameters) {
for(String parameter: parameters) {
Element argument = doc.createElement("argument");
argument.setAttribute("type", "service");
argument.setAttribute("id", parameter);
rootElement.appendChild(argument);
}
}
/**
* The str:split function splits up a string and returns a node set of token
* elements, each containing one token from the string.
* <p>
* The first argument is the string to be split. The second argument is a pattern
* string. The string given by the first argument is split at any occurrence of
* this pattern. For example:
* <pre>
* str:split('a, simple, list', ', ') gives the node set consisting of:
*
* <token>a</token>
* <token>simple</token>
* <token>list</token>
* </pre>
* If the second argument is omitted, the default is the string ' ' (i.e. a space).
*
* @param str The string to be split
* @param pattern The pattern
*
* @return A node set of split tokens
*/
public static NodeList split(String str, String pattern)
{
NodeSet resultSet = new NodeSet();
resultSet.setShouldCacheNodes(true);
boolean done = false;
int fromIndex = 0;
int matchIndex = 0;
String token = null;
while (!done && fromIndex < str.length())
{
matchIndex = str.indexOf(pattern, fromIndex);
if (matchIndex >= 0)
{
token = str.substring(fromIndex, matchIndex);
fromIndex = matchIndex + pattern.length();
}
else
{
done = true;
token = str.substring(fromIndex);
}
Document doc = getDocument();
synchronized (doc)
{
Element element = doc.createElement("token");
Text text = doc.createTextNode(token);
element.appendChild(text);
resultSet.addNode(element);
}
}
return resultSet;
}
private void addRegexpAsParameter(String regexp, Node node, Document document, String url) {
if (StringUtils.isBlank(regexp)) {
return;
}
String builtRegexp;
builtRegexp = buildRegexp(regexp, url);
Logger.getLogger(HeritrixParameterValueModifier.class.getName()).debug(" builtRegexp " + builtRegexp);
if (StringUtils.isNotBlank(builtRegexp) && compileRegexp(regexp)) {
Element element = document.createElement(getElementName());
element.appendChild(document.createTextNode(builtRegexp));
node.appendChild(element);
}
}
/**
* Create a Claims Element for a "role"
*/
private Element createClaims() {
Document doc = DOMUtils.getEmptyDocument();
Element claimsElement =
doc.createElementNS("http://docs.oasis-open.org/ws-sx/ws-trust/200512", "Claims");
claimsElement.setAttributeNS(null, "Dialect", "http://schemas.xmlsoap.org/ws/2005/05/identity");
Element claimType =
doc.createElementNS("http://schemas.xmlsoap.org/ws/2005/05/identity", "ClaimType");
claimType.setAttributeNS(null, "Uri", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role");
claimsElement.appendChild(claimType);
return claimsElement;
}
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
throws MarshalException
{
Document ownerDoc = DOMUtils.getOwnerDocument(parent);
Element rmElem = DOMUtils.createElement(ownerDoc, "RetrievalMethod",
XMLSignature.XMLNS, dsPrefix);
// add URI and Type attributes
DOMUtils.setAttribute(rmElem, "URI", uri);
DOMUtils.setAttribute(rmElem, "Type", type);
// add Transforms elements
if (!transforms.isEmpty()) {
Element transformsElem = DOMUtils.createElement(ownerDoc,
"Transforms",
XMLSignature.XMLNS,
dsPrefix);
rmElem.appendChild(transformsElem);
for (Transform transform : transforms) {
((DOMTransform)transform).marshal(transformsElem,
dsPrefix, context);
}
}
parent.appendChild(rmElem);
// save here node
here = rmElem.getAttributeNodeNS(null, "URI");
}
private void exportLayout(Document m_Doc, Element parent) {
Element layout = m_Doc.createElement("Layout");
//Add attribute
Attr BackColor = m_Doc.createAttribute("BackColor");
Attr ForeColor = m_Doc.createAttribute("ForeColor");
Attr SmoothingMode = m_Doc.createAttribute("SmoothingMode");
Attr PaperSizeName = m_Doc.createAttribute("PaperSizeName");
Attr PaperSizeWidth = m_Doc.createAttribute("PaperSizeWidth");
Attr PaperSizeHeight = m_Doc.createAttribute("PaperSizeHeight");
Attr Landscape = m_Doc.createAttribute("Landscape");
BackColor.setValue(ColorUtil.toHexEncoding(_pageBackColor));
ForeColor.setValue(ColorUtil.toHexEncoding(_pageForeColor));
SmoothingMode.setValue(String.valueOf(_antiAlias));
PaperSizeName.setValue(_paperSize.getName());
PaperSizeWidth.setValue(String.valueOf(_paperSize.getWidth()));
PaperSizeHeight.setValue(String.valueOf(_paperSize.getHeight()));
Landscape.setValue(String.valueOf(_isLandscape));
layout.setAttributeNode(BackColor);
layout.setAttributeNode(ForeColor);
layout.setAttributeNode(SmoothingMode);
layout.setAttributeNode(PaperSizeName);
layout.setAttributeNode(PaperSizeWidth);
layout.setAttributeNode(PaperSizeHeight);
layout.setAttributeNode(Landscape);
parent.appendChild(layout);
//Add layout elements
addLayoutElements(m_Doc, layout);
}
private void marshalSKI(byte[] skid, Node parent, Document doc,
String dsPrefix)
{
Element skidElem = DOMUtils.createElement(doc, "X509SKI",
XMLSignature.XMLNS, dsPrefix);
skidElem.appendChild(doc.createTextNode(Base64.encode(skid)));
parent.appendChild(skidElem);
}
private Element createAppliesToURIElement(String addressUrl) {
Document doc = DOMUtils.getEmptyDocument();
Element appliesTo = doc.createElementNS(STSConstants.WSP_NS, "wsp:AppliesTo");
appliesTo.setAttributeNS(WSS4JConstants.XMLNS_NS, "xmlns:wsp", STSConstants.WSP_NS);
Element uri = doc.createElementNS(STSConstants.WSP_NS, "wsp:URI");
uri.setTextContent(addressUrl);
appliesTo.appendChild(uri);
return appliesTo;
}
/**
* Method addTextElement
*
* @param text
* @param localname
*/
public void addTextElement(String text, String localname) {
Element e = XMLUtils.createElementInSignatureSpace(this.doc, localname);
Text t = this.doc.createTextNode(text);
e.appendChild(t);
this.constructionElement.appendChild(e);
XMLUtils.addReturnToElement(this.constructionElement);
}
/**
* Equivalence class partitioning with state and input values orientation
* for public void setParameter(String name, Object value) throws
* DOMException, <br>
* <b>pre-conditions</b>: the doc contains one entity and one entity
* reference, <br>
* <b>name</b>: entities <br>
* <b>value</b>: false. <br>
* <b>Expected results</b>: the entity and the entity reference are removed
*/
@Test
public void testEntities002() {
Document doc = null;
try {
doc = loadDocument(null, test1_xml);
} catch (Exception e) {
Assert.fail(e.getMessage());
}
DOMConfiguration config = doc.getDomConfig();
if (!config.canSetParameter("entities", Boolean.FALSE)) {
Assert.fail("setting 'entities' to false is not supported");
}
Element root = doc.getDocumentElement();
root.appendChild(doc.createEntityReference("x"));
// TODO: remove debug
NamedNodeMap entities = doc.getDoctype().getEntities();
Entity entityX = (Entity) entities.getNamedItem("x");
System.err.println();
System.err.println("Entity x: " + entityX.getTextContent());
System.err.println();
config.setParameter("entities", Boolean.FALSE);
setHandler(doc);
doc.normalizeDocument();
Node child = root.getFirstChild();
// TODO: restore test, exclude for now to allow other tests to run
/*
* if (child == null) { fail("root has no child"); } if
* (child.getNodeType() != Node.TEXT_NODE ||
* !"X".equals(child.getNodeValue())) { fail("root's child is " + child
* + ", expected text node with value 'X'"); }
*
* if (doc.getDoctype() == null) { fail("no doctype found"); }
*
* if (doc.getDoctype().getEntities() != null &&
* doc.getDoctype().getEntities().getNamedItem("x") != null) {
* fail("entity with name 'x' is found, expected to be removed"); }
*/
return; // Status.passed("OK");
}
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
throws MarshalException
{
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Marshalling Reference");
}
Document ownerDoc = DOMUtils.getOwnerDocument(parent);
refElem = DOMUtils.createElement(ownerDoc, "Reference",
XMLSignature.XMLNS, dsPrefix);
// set attributes
DOMUtils.setAttributeID(refElem, "Id", id);
DOMUtils.setAttribute(refElem, "URI", uri);
DOMUtils.setAttribute(refElem, "Type", type);
// create and append Transforms element
if (!allTransforms.isEmpty()) {
Element transformsElem = DOMUtils.createElement(ownerDoc,
"Transforms",
XMLSignature.XMLNS,
dsPrefix);
refElem.appendChild(transformsElem);
for (Transform transform : allTransforms) {
((DOMStructure)transform).marshal(transformsElem,
dsPrefix, context);
}
}
// create and append DigestMethod element
((DOMDigestMethod)digestMethod).marshal(refElem, dsPrefix, context);
// create and append DigestValue element
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Adding digestValueElem");
}
Element digestValueElem = DOMUtils.createElement(ownerDoc,
"DigestValue",
XMLSignature.XMLNS,
dsPrefix);
if (digestValue != null) {
digestValueElem.appendChild
(ownerDoc.createTextNode(Base64.encode(digestValue)));
}
refElem.appendChild(digestValueElem);
parent.appendChild(refElem);
here = refElem.getAttributeNodeNS(null, "URI");
}
private void addEMIItem(String ident, ItemTextIfc itemText, Item itemXml) {
//main node resprocessing
Element resprocessing = createElement("resprocessing", itemXml);
itemXml.addElement("item", resprocessing);
//outcomes with the scores and required count
Element outcomes = createElement("outcomes", itemXml);
resprocessing.appendChild(outcomes);
//decvar for score
Element decvarScore = createElement("decvar", itemXml);
decvarScore.setAttribute("defaultval", "0");
decvarScore.setAttribute("varname", "SCORE");
decvarScore.setAttribute("vartype", "Double");
outcomes.appendChild(decvarScore);
//decvar for required count
Element decvarRequired = createElement("decvar", itemXml);
decvarRequired.setAttribute("defaultval", String.valueOf(itemText.getEmiCorrectOptionLabels().length()));
decvarRequired.setAttribute("maxvalue", itemText.getRequiredOptionsCount().toString());
decvarRequired.setAttribute("minvalue", "0");
decvarRequired.setAttribute("varname", "requiredOptionsCount");
decvarRequired.setAttribute("vartype", "Integer");
outcomes.appendChild(decvarRequired);
//decvar for score user set
Element decvarScoreUserSet = createElement("decvar", itemXml);
decvarScoreUserSet.setAttribute("varname", "scoreUserSet");
decvarScoreUserSet.setAttribute("vartype", "String");
outcomes.appendChild(decvarScoreUserSet);
//Item Text
Element interpretvar = createElement("interpretvar", itemXml);//Testing
outcomes.appendChild(interpretvar);//Testing
Element material = createElement("material", itemXml);//Testing
interpretvar.appendChild(material);//Testing
Element mattext = createElement("mattext", itemXml);//Testing
mattext.setTextContent(XmlUtil.convertToSingleCDATA(itemText.getText()));//Testing
material.appendChild(mattext);//Testing
if(itemText.getHasAttachment()){
setAttachments(itemText.getItemTextAttachmentSet(), itemXml, material);
}
double score = 0.0;
double discount = 0.0;
//respcondition for every correct option
for(AnswerIfc answer: itemText.getAnswerArraySorted()){
decvarScoreUserSet.setAttribute("defaultval", answer.getGrade());
Element respcondition = createElement("respcondition", itemXml);
respcondition.setAttribute("continue", "Yes");
respcondition.setAttribute("title", answer.getIsCorrect()?"CORRECT":"INCORRECT");
resprocessing.appendChild(respcondition);
//conditionvar for correct answers
Element conditionvar = createElement("conditionvar", itemXml);
respcondition.appendChild(conditionvar);
Element varequal = createElement("varequal", itemXml);
varequal.setAttribute("case", "Yes");
varequal.setAttribute("respident", ident);
varequal.setTextContent(answer.getLabel());
conditionvar.appendChild(varequal);
//setvar for action
Element setvar = createElement("setvar", itemXml);
if(answer.getIsCorrect()){
setvar.setAttribute("action", "Add");
setvar.setTextContent(String.valueOf(getDouble(answer.getScore())));
score += getDouble(answer.getScore());
}else{
setvar.setAttribute("action", "Subtract");
setvar.setTextContent(String.valueOf(Math.abs(getDouble(answer.getDiscount()))));
discount += getDouble(answer.getDiscount());
}
setvar.setAttribute("varname", "SCORE");
respcondition.appendChild(setvar);
}
//set the scores
decvarScore.setAttribute("maxvalue", String.valueOf(getDouble(score)));
decvarScore.setAttribute("minvalue", "0");//String.valueOf(getDouble(discount)));
}