下面列出了org.w3c.dom.Document#appendChild ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private XMLSignature prepareEnvelopingSignature(Document doc,
String id,
String referenceId,
String sigAlgo,
String digestAlgo) throws Exception {
Element docEl = doc.getDocumentElement();
Document newDoc = DOMUtils.createDocument();
doc.removeChild(docEl);
newDoc.adoptNode(docEl);
Element object = newDoc.createElementNS(Constants.SignatureSpecNS, "ds:Object");
object.appendChild(docEl);
docEl.setAttributeNS(null, "Id", id);
docEl.setIdAttributeNS(null, "Id", true);
XMLSignature sig = new XMLSignature(newDoc, "", sigAlgo);
newDoc.appendChild(sig.getElement());
sig.getElement().appendChild(object);
Transforms transforms = new Transforms(newDoc);
transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
sig.addDocument(referenceId, transforms, digestAlgo);
return sig;
}
/**
* Transfers the paramsMap into a Document.
*
* @param operationName as root element.
* @return the created Document.
*/
private Document mapToDoc(final String operationName, final Map<String, String> paramsMap) {
Document document;
final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
final DocumentBuilder documentBuilder;
try {
documentBuilder = documentBuilderFactory.newDocumentBuilder();
} catch (final ParserConfigurationException e) {
e.printStackTrace();
return null;
}
document = documentBuilder.newDocument();
final Element rootElement = document.createElement(operationName);
document.appendChild(rootElement);
for (final Entry<String, String> entry : paramsMap.entrySet()) {
final Element mapElement = document.createElement(entry.getKey());
mapElement.setTextContent(entry.getValue());
rootElement.appendChild(mapElement);
}
return document;
}
/** Gets the agent program (Beliefs and plans) as XML */
public Document getAgProgram() {
if (builder == null) {
try {
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (Exception e) {
logger.log(Level.SEVERE, "Error creating XML builder\n");
return null;
}
}
Document document = builder.newDocument();
Element ag = (Element) document.createElement("agent");
if (getASLSrc() != null && getASLSrc().length() > 0) {
ag.setAttribute("source", getASLSrc());
}
ag.appendChild(bb.getAsDOM(document));
ag.appendChild(pl.getAsDOM(document));
document.appendChild(ag);
return document;
}
/**
* Returns a root memento for writing a document.
*
* @param type
* the element node type to create on the document
* @return the root memento for writing a document
*/
public static XMLMemento createWriteRoot(String type)
{
Document document;
try
{
document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element element = document.createElement(type);
document.appendChild(element);
return new XMLMemento(document, element);
}
catch (ParserConfigurationException e)
{
// throw new Error(e);
throw new Error(e.getMessage());
}
}
/**
* Save a single emitter to the XML file
*
* @param out
* The location to which we should save
* @param emitter
* The emitter to store to the XML file
* @throws IOException
* Indicates a failure to write or encode the XML
*/
public static void saveEmitter(OutputStream out, ConfigurableEmitter emitter)
throws IOException {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document document = builder.newDocument();
document.appendChild(emitterToElement(document, emitter));
Result result = new StreamResult(new OutputStreamWriter(out,
"utf-8"));
DOMSource source = new DOMSource(document);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer xformer = factory.newTransformer();
xformer.setOutputProperty(OutputKeys.INDENT, "yes");
xformer.transform(source, result);
} catch (Exception e) {
Log.error(e);
throw new IOException("Failed to save emitter");
}
}
public static Document fromRootNode(Node node) {
if (node == null) {
return null;
}
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
// YA we dun fucked up...
// LOGGER.error(e);
return null;
}
Document result = builder.newDocument();
Node imported = result.importNode(node, true);
result.appendChild(imported);
return result;
}
public void saveToFile(final @Nonnull File file) {
try {
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
final Element element = document.createElement(MAINFILE_ELEMENT);
document.appendChild(element);
this.saveValueToXML(element);
// Create transformer.
final Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
// Write to file and transform.
transformer.transform(new DOMSource(document), new StreamResult(new FileOutputStream(file)));
} catch (ParserConfigurationException | TransformerFactoryConfigurationError
| FileNotFoundException | TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Convert a SQL ResultSet object to a XML Element. The
* <code>addTypeInfo</code> argument specifies whether or not to add a "type"
* attribute to each field that has the result of {@link Class#getName()} as
* its value.
*
* @param ignoreTypeInfo
* if type of the result set has to be ignored and just its
* toString() value is to be set in the XML
*/
public static Element resultSetToXMLElement(ResultSet rs,
boolean addTypeInfo, boolean ignoreTypeInfo) throws SQLException,
IOException, ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element resultSetElement = doc.createElement("resultSet");
doc.appendChild(resultSetElement);
if (rs != null) {
ResultSetMetaData rsMD = rs.getMetaData();
int numCols = rsMD.getColumnCount();
while (rs.next()) {
Element resultElement = doc.createElement("row");
resultSetElement.appendChild(resultElement);
for (int index = 1; index <= numCols; ++index) {
String colName = rsMD.getColumnName(index);
Element fieldElement = doc.createElement("field");
fieldElement.setAttribute("name", colName);
if (addTypeInfo && !ignoreTypeInfo) {
fieldElement.setAttribute("type", rs.getObject(index).getClass()
.getName());
}
String valStr = rs.getString(index);
if (valStr == null) {
valStr = "NULL";
}
if (valStr.length() > 0) {
fieldElement.appendChild(doc.createTextNode(valStr));
}
resultElement.appendChild(fieldElement);
}
}
rs.close();
}
return resultSetElement;
}
private static Document toXML() throws ParserConfigurationException {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element root = doc.createElement("extensions");
doc.appendChild(root);
for (ManagedExtension ext : MANAGED_EXTENSIONS.values()) {
root.appendChild(ext.toXML(doc));
}
return doc;
}
public Document xmlFromBean(final B bean) throws Exception {
final DocumentBuilder builder = factory.newDocumentBuilder();
final Document doc = builder.newDocument();
final Element rootNode = xmlFromBean(bean, doc);
rootNode.setAttributeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI,
"xsi:schemaLocation", SCHEMA_LOCATION);
doc.appendChild(rootNode);
return doc;
}
/**
* Builds modsCollection from mods of articles.
*/
Document mergeElements(List<Article> articles) throws DOMException {
Document doc = db.newDocument();
Element root = doc.createElementNS(ModsConstants.NS, "modsCollection");
for (Article article : articles) {
Element modsElm = article.getModsElement();
Node n = doc.adoptNode(modsElm);
root.appendChild(n);
}
doc.appendChild(root);
return doc;
}
/**
* Look up a List of Section XML from Assessment Xml
* @return a List of Section XML objects
*/
public List getSectionXmlList(Assessment assessmentXml)
{
List nodeList = assessmentXml.selectNodes("//section");
List sectionXmlList = new ArrayList();
// now convert our list of Nodes to a list of section xml
for (int i = 0; i < nodeList.size(); i++)
{
try
{
Node node = (Node) nodeList.get(i);
// create a document for a section xml object
Document sectionDoc = XmlUtil.createDocument();
// Make a copy for inserting into the new document
Node importNode = sectionDoc.importNode(node, true);
// Insert the copy into sectionDoc
sectionDoc.appendChild(importNode);
Section sectionXml = new Section(sectionDoc,
this.getQtiVersion());
// add the new section xml object to the list
sectionXmlList.add(sectionXml);
}
catch (DOMException ex)
{
log.error(ex.getMessage(), ex);
}
}
return sectionXmlList;
}
protected Document buildEventDescriptionDocument(Event e, String TAG) throws ParserConfigurationException {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element event = doc.createElement(TAG);
doc.appendChild(event);
event.setAttribute(EVENT_INTERACTION, (e.getInteraction() != null)?e.getInteraction():"");
event.setAttribute(EVENT_VALUE, (e.getValue() != null)?e.getValue():"");
event.setAttribute(EVENT_UID, Long.toString(e.getEventUID()));
if (e.getWidget() != null) {
Element widget = null;
if (e.getWidget() != null) {
widget = this.buildWidgetDescriptionDocument( e.getWidget() ).getDocumentElement();
//event.appendChild( doc.importNode((Node)widget, true) );
event.appendChild(importElement(doc, widget)) ;
} else {
widget = doc.createElement(WIDGET);
event.appendChild( widget );
}
}
if (e.getInputs() != null) {
for (Input i : e.getInputs())
{
Element input = this.buildInputDescriptionDocument(i).getDocumentElement();
//event.appendChild( doc.importNode((Node)input, true) );
event.appendChild(importElement(doc, input)) ;
}
}
return doc;
}
private static DocumentFragment staticPlaceholder(String imageName, String id, boolean block) {
String url = Editor.getContextPath()+"/placeholders/" + imageName;
// Create a DOM document to take the results
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document document=null;
try {
document = factory.newDocumentBuilder().newDocument();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Element xhtmlBlock = document.createElement("p");
// document.appendChild(xhtmlBlock);
Element xhtmlBlock = document.createElement("img");
document.appendChild(xhtmlBlock);
xhtmlBlock.setAttribute("src", url);
xhtmlBlock.setAttribute("id", id);
if(block) {
xhtmlBlock.setAttribute("style", "display:block");
}
DocumentFragment docfrag = document.createDocumentFragment();
docfrag.appendChild(document.getDocumentElement());
return docfrag;
}
private Document getXMLAsDocumentObject(String startValidTime,
String endValidTime, String address, String uri) throws Exception {
Document domDocument = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().newDocument();
Element root = domDocument.createElement("root");
// System start and End time
Node systemNode = root.appendChild(domDocument.createElement("system"));
systemNode.appendChild(domDocument.createElement(systemStartERIName));
systemNode.appendChild(domDocument.createElement(systemEndERIName));
// Valid start and End time
Node validNode = root.appendChild(domDocument.createElement("valid"));
Node validStartNode = validNode.appendChild(domDocument
.createElement(validStartERIName));
validStartNode.appendChild(domDocument.createTextNode(startValidTime));
validNode.appendChild(validStartNode);
Node validEndNode = validNode.appendChild(domDocument
.createElement(validEndERIName));
validEndNode.appendChild(domDocument.createTextNode(endValidTime));
validNode.appendChild(validEndNode);
// Address
Node addressNode = root.appendChild(domDocument.createElement("Address"));
addressNode.appendChild(domDocument.createTextNode(address));
// uri
Node uriNode = root.appendChild(domDocument.createElement("uri"));
uriNode.appendChild(domDocument.createTextNode(uri));
domDocument.appendChild(root);
return domDocument;
}
/**
* Serialize the resource into XML, adding an element to the doc under the top of the stack element.
*
* @param doc
* The DOM doc to contain the XML (or null for a string return).
* @param stack
* The DOM elements, the top of which is the containing element of the new "resource" element.
* @return The newly added element.
*/
public Element toXml(Document doc, Stack stack)
{
Element event = doc.createElement("event");
if (stack.isEmpty())
{
doc.appendChild(event);
}
else
{
((Element) stack.peek()).appendChild(event);
}
stack.push(event);
event.setAttribute("id", getId());
event.setAttribute("range", getRange().toString());
// add access
event.setAttribute("access", m_access.toString());
// add groups
if ((m_groups != null) && (m_groups.size() > 0))
{
for (Iterator i = m_groups.iterator(); i.hasNext();)
{
String group = (String) i.next();
Element sect = doc.createElement("group");
event.appendChild(sect);
sect.setAttribute("authzGroup", group);
}
}
// properties
m_properties.toXml(doc, stack);
if ((m_attachments != null) && (m_attachments.size() > 0))
{
for (int i = 0; i < m_attachments.size(); i++)
{
Reference attch = (Reference) m_attachments.get(i);
Element attachment = doc.createElement("attachment");
event.appendChild(attachment);
attachment.setAttribute("relative-url", attch.getReference());
}
}
// rules
if (m_singleRule != null)
{
Element rules = doc.createElement("rules");
event.appendChild(rules);
stack.push(rules);
// the rule
m_singleRule.toXml(doc, stack);
// the exculsions
if (m_exclusionRule != null)
{
m_exclusionRule.toXml(doc, stack);
}
stack.pop();
}
stack.pop();
return event;
}
/**
* This takes a RecordingData object and puts it in XML.
* @return the XML as an org.w3c.dom.Document
*/
public Document getXMLDataModel()
{
Document document = null;
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
try
{
DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
document = documentBuilder.newDocument();
}
catch(ParserConfigurationException e)
{
log.error(e.getMessage(), e);
}
if (document == null) {
log.error("document is null");
return null;
}
//add audio setup data to XML document
//root
Element recordingData = document.createElement("RecordingData");
//sub elements
Element agentName = document.createElement("AgentName");
Element agentId = document.createElement("AgentId");
Element courseAssignmentContext = document.createElement("CourseAssignmentContext");
Element fileExtension = document.createElement("FileExtension");
Element fileName = document.createElement("FileName");
Element limit = document.createElement("Limit");
Element dir = document.createElement("Dir");
Element seconds = document.createElement("Seconds");
Element appName = document.createElement("AppName");
Element imageURL = document.createElement("ImageURL");
agentName.appendChild(document.createTextNode(this.getAgentName()));
agentId.appendChild(document.createTextNode(this.getAgentId()));
courseAssignmentContext.appendChild(
document.createTextNode(this.getCourseAssignmentContext()));
fileExtension.appendChild(document.createTextNode(this.getFileExtension()));
fileName.appendChild(document.createTextNode(this.getFileName()));
limit.appendChild(document.createTextNode(this.getLimit()));
dir.appendChild(document.createTextNode(this.getDir()));
seconds.appendChild(document.createTextNode(this.getSeconds()));
appName.appendChild(document.createTextNode(this.getAppName()));
imageURL.appendChild(document.createTextNode(this.getImageURL()));
recordingData.appendChild(agentName);
recordingData.appendChild(agentId);
recordingData.appendChild(courseAssignmentContext);
recordingData.appendChild(fileExtension);
recordingData.appendChild(fileName);
recordingData.appendChild(limit);
recordingData.appendChild(dir);
recordingData.appendChild(seconds);
recordingData.appendChild(appName);
recordingData.appendChild(imageURL);
document.appendChild(recordingData);
// return the recording data available in XML
return document;
}
@Override
public void serialize(final FlowController controller, final OutputStream os) throws FlowSerializationException {
try {
// create a new, empty document
final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docFactory.setNamespaceAware(true);
final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
final Document doc = docBuilder.newDocument();
// populate document with controller state
final Element rootNode = doc.createElement("flowController");
rootNode.setAttribute("encoding-version", MAX_ENCODING_VERSION);
doc.appendChild(rootNode);
addTextElement(rootNode, "maxTimerDrivenThreadCount", controller.getMaxTimerDrivenThreadCount());
addTextElement(rootNode, "maxEventDrivenThreadCount", controller.getMaxEventDrivenThreadCount());
addProcessGroup(rootNode, controller.getGroup(controller.getRootGroupId()), "rootGroup");
// Add root-level controller services
final Element controllerServicesNode = doc.createElement("controllerServices");
rootNode.appendChild(controllerServicesNode);
for (final ControllerServiceNode serviceNode : controller.getRootControllerServices()) {
addControllerService(controllerServicesNode, serviceNode);
}
final Element reportingTasksNode = doc.createElement("reportingTasks");
rootNode.appendChild(reportingTasksNode);
for (final ReportingTaskNode taskNode : controller.getAllReportingTasks()) {
addReportingTask(reportingTasksNode, taskNode, encryptor);
}
final DOMSource domSource = new DOMSource(doc);
final StreamResult streamResult = new StreamResult(new BufferedOutputStream(os));
// configure the transformer and convert the DOM
final TransformerFactory transformFactory = TransformerFactory.newInstance();
final Transformer transformer = transformFactory.newTransformer();
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// transform the document to byte stream
transformer.transform(domSource, streamResult);
} catch (final ParserConfigurationException | DOMException | TransformerFactoryConfigurationError | IllegalArgumentException | TransformerException e) {
throw new FlowSerializationException(e);
}
}
private Document populateDocument(Document document, SourceOfRandomness random, GenerationStatus status) {
Element root = document.createElement(makeString(random, status));
populateElement(document, root, random, status, 0);
document.appendChild(root);
return document;
}
/** {@inheritDoc} */
@Override
public void saveKeyFrameMeta(File file, KeyFrameMeta meta) {
if (meta.positions.length == 0) {
// Don't store empty meta informations
return;
}
Document dom;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
//get an instance of builder
DocumentBuilder db = dbf.newDocumentBuilder();
//create an instance of DOM
dom = db.newDocument();
} catch (ParserConfigurationException pce) {
log.error("Error while creating document.", pce);
return;
}
// Create file and add keyframe informations
Element root = dom.createElement("FrameMetadata");
root.setAttribute("modified", String.valueOf(file.lastModified()));
root.setAttribute("duration", String.valueOf(meta.duration));
root.setAttribute("audioOnly", meta.audioOnly ? "true" : "false");
dom.appendChild(root);
for (int i = 0; i < meta.positions.length; i++) {
Element node = dom.createElement("KeyFrame");
node.setAttribute("position", String.valueOf(meta.positions[i]));
node.setAttribute("timestamp", String.valueOf(meta.timestamps[i]));
root.appendChild(node);
}
String filename = file.getAbsolutePath() + ".meta";
try {
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
t.transform(new DOMSource(dom), new StreamResult(new File(filename)));
} catch (Exception err) {
log.error("could not save keyframe data", err);
}
}