下面列出了org.w3c.dom.Document#createElement ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Returns the xml representation of the registered configurables.
*
* @return the configurable as XML document
* @since 6.2.0
*/
public Document getConfigurablesAsXML(AbstractConfigurator<? extends Configurable> configurator, boolean onlyLocal) {
Document doc = XMLTools.createDocument();
Element root = doc.createElement(CONFIGURATION_TAG);
doc.appendChild(root);
for (Configurable configurable : configurables.get(configurator.getTypeId()).values()) {
try {
checkAccess(configurator.getTypeId(), configurable.getName(), null);
} catch (ConfigurationException e) {
continue;
}
if (onlyLocal && configurable.getSource() != null) {
continue;
}
root.appendChild(toXML(doc, configurator, configurable));
}
return doc;
}
/**
* Encode the data source properties to XML.
*
* @param doc the doc
* @param root the root
* @param elementName the element name
*/
@Override
public void encodeXML(Document doc, Element root, String elementName) {
if ((doc == null) || (root == null) || (elementName == null)) {
return;
}
Element dataSourceElement = doc.createElement(elementName);
for (Entry<String, Object> entry : propertyMap.entrySet()) {
Element element = doc.createElement(entry.getKey());
element.appendChild(doc.createTextNode((String) entry.getValue()));
dataSourceElement.appendChild(element);
}
root.appendChild(dataSourceElement);
}
@Override
public Node storeToXML(Document doc) {
Object value = getUnwrappedValue();
org.w3c.dom.Element el = doc.createElement(XML_FONT_ROOT);
el.setAttribute(ATTR_RELATIVE, Boolean.TRUE.toString());
if (!(value instanceof NbFont)) {// || propertyValue.absolute) {
org.w3c.dom.Node absNode = ((XMLPropertyEditor)delegateEditor).storeToXML(doc);
el.appendChild(absNode);
} else {
NbFont propertyValue = (NbFont) value;
org.w3c.dom.Element subel = doc.createElement(XML_FONT);
el.appendChild(subel);
subel.setAttribute(ATTR_RELATIVE_SIZE, Boolean.toString(!propertyValue.absoluteSize));
subel.setAttribute(ATTR_SIZE, Integer.toString(propertyValue.size));
if (propertyValue.italic != null) {
subel.setAttribute(ATTR_ITALIC_CHANGE, propertyValue.italic.toString());
}
if (propertyValue.bold != null) {
subel.setAttribute(ATTR_BOLD_CHANGE, propertyValue.bold.toString());
}
subel.setAttribute(ATTR_COMP_NAME, ((RADProperty)property).getRADComponent().getName());
subel.setAttribute(ATTR_PROP_NAME, property.getName());
}
return el;
}
/**
* Create the repository meta data file, for scraping
*
* @param context
* @return the document
*/
private Document makeRepoMetaData ( final AggregationContext context )
{
final Document doc = this.xml.create ();
// create document
final Element root = doc.createElement ( "repository-metadata" );
doc.appendChild ( root );
addElement ( root, "version", "1.0.0" );
addElement ( root, "id", context.getChannelId () );
addElement ( root, "name", context.getChannelId () );
addElement ( root, "layout", "maven2" );
addElement ( root, "policy", "mixed" );
addElement ( root, "url", makeUrl ( context.getChannelId () ) );
return doc;
}
public static void sample()throws Exception {
int no = 2;
String root = "EnterRoot";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document d = db.newDocument();
Element eRoot = d.createElement(root);
d.appendChild(eRoot);
for (int i = 1; i <= no; i++){
String element = "EnterElement";
String data = "Enter the data";
Element e = d.createElement(element);
e.appendChild(d.createTextNode(data));
eRoot.appendChild(e);
}
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
DOMSource source = new DOMSource(d);
StreamResult result = new StreamResult(System.out);
t.transform(source, result);
}
private void printResults(String className) {
Set<TestMethodReportDefinition> methodDefinitions = testsRegistry.removeClassTestMethods(className);
Document doc = getDocumentBuilder().newDocument();
Element rootElement = null;
long totalTime = 0;
int testsTotal = 0;
int testsFailed = 0;
for (TestMethodReportDefinition def : methodDefinitions) {
testsRegistry.removeMethodDefinitionById(def.getFullMethodName());
if (filePerMethod || rootElement == null) {
rootElement = createTestSuiteElement(className, doc);
totalTime = 0;
testsTotal = 0;
testsFailed = 0;
}
TestMethodCompletionResult completionResult = resultsHolder.pollCompletionResult(def.getFullMethodName());
LatencyCounter mainCounter = completionResult.getMainCounter();
PerformanceRequirement requirement = completionResult.getPerfRequirement();
List<TestResult> testResults = null;
testResults = resultsHolder.pollTestResults(def.getFullMethodName());
if (testResults != null) {
testsTotal += testResults.size();
for (TestResult result : testResults) {
Element currentTest = doc.createElement(TESTCASE);
rootElement.appendChild(currentTest);
boolean isFailed = formatTestCase(def, currentTest, result, requirement, doc);
if (isFailed) {
testsFailed++;
}
}
}
totalTime += mainCounter.totalLatency();
if (filePerMethod) {
rootElement.setAttribute(TIME, String.valueOf(totalTime / 1000.0));
rootElement.setAttribute(TESTS, "" + testsTotal);
rootElement.setAttribute(FAILURES, "" + testsFailed);
printElement(rootElement, def.getFullMethodName());
}
}
if (!filePerMethod) {
rootElement.setAttribute(TIME, String.valueOf(totalTime / 1000.0));
rootElement.setAttribute(TESTS, "" + testsTotal);
rootElement.setAttribute(FAILURES, "" + testsFailed);
printElement(rootElement, className);
}
}
/**
* Returns validation errors in a root container node.
* The root container ({@code <errors>}) contains a list
* of {@code <error>} elements containing error
* messages as text content.
*
* @return Root element containing list of errors
*/
public Element toRootElement() {
Document doc = null;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.newDocument();
} catch (Exception e) {
jlogger.log(Level.SEVERE, "validate", e);
e.printStackTrace();
// Fortify Mod: if we get here then there is no point in going further
return null;
}
Element root = doc.createElement("errors");
doc.appendChild(root);
ErrorIterator errIterator = iterator();
while (errIterator.hasNext()) {
ValidationError err = errIterator.next();
Element elem = doc.createElement("error");
elem.setTextContent(err.getMessage());
root.appendChild(elem);
}
return root;
}
public void testFindLine() throws Exception {
Document script = ja.readCustomScript("special.xml");
Element target = script.createElement("target");
target.setAttribute("name", "targ1");
target.appendChild(script.createElement("task1"));
target.appendChild(script.createElement("task2"));
script.getDocumentElement().appendChild(target);
target = script.createElement("target");
target.setAttribute("name", "targ2");
target.appendChild(script.createElement("task3"));
script.getDocumentElement().appendChild(target);
ja.writeCustomScript(script, "special.xml");
FileObject scriptFile = prj.getProjectDirectory().getFileObject("special.xml");
assertNotNull(scriptFile);
//0 <?xml?>
//1 <project>
//2 <target name="targ1">
//3 <task1/>
//4 <task2/>
//5 </>
//6 <target name="targ2">
//7 <task3/>
//8 </>
//9 </>
assertEquals(2, JavaActions.findLine(scriptFile, "targ1", "target", "name"));
assertEquals(6, JavaActions.findLine(scriptFile, "targ2", "target", "name"));
assertEquals(-1, JavaActions.findLine(scriptFile, "no-such-targ", "target", "name"));
// Try w/ project.xml which uses namespaces, too.
FileObject pxml = prj.getProjectDirectory().getFileObject("nbproject/project.xml");
assertNotNull(pxml);
assertTrue(JavaActions.findLine(pxml, "build", "action", "name") != -1);
assertEquals(-1, JavaActions.findLine(pxml, "nonexistent", "action", "name"));
}
public boolean setHttpProxyOptions(String[] httpProxyOptions){
Document domainDoc = getDomainDocument();
NodeList javaConfigNodeList = domainDoc.getElementsByTagName("java-config");
if (javaConfigNodeList == null || javaConfigNodeList.getLength() == 0) {
return false;
}
//Iterates through the existing proxy attributes and deletes them
removeProxyOptions(domainDoc, javaConfigNodeList.item(0));
//Add new set of proxy options
for(int j=0; j<httpProxyOptions.length; j++){
String option = httpProxyOptions[j];
Element jvmOptionsElement = domainDoc.createElement(CONST_JVM_OPTIONS);
Text proxyOption = domainDoc.createTextNode(option);
jvmOptionsElement.appendChild(proxyOption);
javaConfigNodeList.item(0).appendChild(jvmOptionsElement);
}
return saveDomainScriptFile(domainDoc, getDomainLocation(), false);
}
/**
* Generates the XML for an event.
* @param doc
* @param parent
* @param event
* @param eventNodeName
* @param containingTimeRange
* @param forceMinimumTime
* @param hideGroupIfNoSpace
* @param performEndTimeKludge
* @param baseCalendarService
*/
private void generateXMLEvent(Document doc, Element parent, CalendarEvent event, String eventNodeName,
TimeRange containingTimeRange, boolean forceMinimumTime, boolean hideGroupIfNoSpace, boolean performEndTimeKludge, BaseCalendarService baseCalendarService)
{
Element eventElement = doc.createElement(eventNodeName);
TimeRange trimmedTimeRange = trimTimeRange(containingTimeRange, event.getRange());
// Optionally force the event to have a minimum time slot.
if (forceMinimumTime)
{
trimmedTimeRange = roundRangeToMinimumTimeInterval(trimmedTimeRange);
}
// Add the "from" time as an attribute.
eventElement.setAttribute(FROM_ATTRIBUTE_STRING, getTimeString(trimmedTimeRange.firstTime()));
// Add the "to" time as an attribute.
Time endTime = null;
// Optionally adjust the end time
if (performEndTimeKludge)
{
endTime = performEndMinuteKludge(trimmedTimeRange.lastTime().breakdownLocal());
}
else
{
endTime = trimmedTimeRange.lastTime();
}
eventElement.setAttribute(TO_ATTRIBUTE_STRING, getTimeString(endTime));
//
// Add the group (really "site") node
// Provide that we have space or if we've been told we need to display it.
//
if (!hideGroupIfNoSpace || trimmedTimeRange.duration() > MINIMUM_EVENT_LENGTH_IN_MSECONDS)
{
writeStringNodeToDom(doc, eventElement, GROUP_NODE, event.getSiteName());
}
// Add the display name node.
writeStringNodeToDom(doc, eventElement, TITLE_NODE, event.getDisplayName());
// Add the event type node.
writeStringNodeToDom(doc, eventElement, TYPE_NODE, rb.getString(getEventDescription(event.getType())));
// Add the place/location node.
writeStringNodeToDom(doc, eventElement, PLACE_NODE, event.getLocation());
// If a "Faculty" extra field is present, then add the node.
writeStringNodeToDom(doc, eventElement, FACULTY_NODE, event.getField(FACULTY_EVENT_ATTRIBUTE_NAME));
// If a "Description" field is present, then add the node.
writeStringNodeToDom(doc, eventElement, DESCRIPTION_NODE, event.getDescription());
parent.appendChild(eventElement);
}
private void makePom ( final MavenReference ref, final Path versionBase, final Set<MavenDependency> deps, final IInstallableUnit iu ) throws Exception
{
final Document doc = this.documentBuilder.newDocument ();
final Element project = doc.createElementNS ( "http://maven.apache.org/POM/4.0.0", "project" );
project.setAttributeNS ( "http://www.w3.org/2001/XMLSchema-instance", "xsi:schemaLocation", "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" );
doc.appendChild ( project );
addElement ( project, "modelVersion", "4.0.0" );
addElement ( project, "groupId", ref.getGroupId () );
addElement ( project, "artifactId", ref.getArtifactId () );
addElement ( project, "version", ref.getVersion () );
addElement ( project, "url", makeProjectUrl ( iu ) );
// name and description
String name = iu.getProperty ( "org.eclipse.equinox.p2.name", null );
if ( name == null )
{
name = String.format ( "%s:%s", ref.getGroupId (), ref.getArtifactId () );
}
String description = iu.getProperty ( "org.eclipse.equinox.p2.description", null );
if ( description == null )
{
description = name;
}
addElement ( project, "name", name );
addElement ( project, "description", description );
addOrganization ( project );
addDevelopers ( project );
// license
final List<License> lics = this.licenseProvider.getLicenses ( iu );
if ( lics != null )
{
addLicense ( project, lics );
}
else if ( ref.getArtifactId ().startsWith ( "org.eclipse." ) )
{
addLicense ( project, singletonList ( EPL ) );
}
else
{
this.errors.add ( String.format ( "%s: no license information", ref ) );
}
makeScm ( iu, doc, project, versionBase, ref );
if ( !deps.isEmpty () )
{
final Element depsEle = doc.createElement ( "dependencies" );
project.appendChild ( depsEle );
for ( final MavenDependency dep : deps )
{
final Element depEle = doc.createElement ( "dependency" );
depsEle.appendChild ( depEle );
addElement ( depEle, "groupId", dep.getGroupId () );
addElement ( depEle, "artifactId", dep.getArtifactId () );
addElement ( depEle, "version", dep.getVersion () );
if ( dep.isOptional () )
{
addElement ( depEle, "optional", "true" );
}
}
}
final Path pomFile = versionBase.resolve ( ref.getArtifactId () + "-" + ref.getVersion () + ".pom" );
saveXml ( doc, pomFile );
makeChecksum ( "MD5", pomFile, versionBase.resolve ( ref.getArtifactId () + "-" + ref.getVersion () + ".pom.md5" ) );
makeChecksum ( "SHA1", pomFile, versionBase.resolve ( ref.getArtifactId () + "-" + ref.getVersion () + ".pom.sha1" ) );
addMetaDataVersion ( ref );
}
public static Element addEntity(final Document doc, final Element entity, final String entityName, final String entityType) {
final Element newEntity = doc.createElement("entity");
entity.appendChild(newEntity);
if (entityType != null) {
newEntity.setAttribute("type", entityType);
}
if (entityName != null) {
newEntity.setAttribute("name", entityName);
}
return newEntity;
}
public void applyXSW8(Document document){
Element evilAssertion = (Element) document.getElementsByTagNameNS("*", "Assertion").item(0);
Element originalSignature = (Element) evilAssertion.getElementsByTagNameNS("*", "Signature").item(0);
Element assertion = (Element) evilAssertion.cloneNode(true);
Element copiedSignature = (Element) assertion.getElementsByTagNameNS("*", "Signature").item(0);
assertion.removeChild(copiedSignature);
Element object = document.createElement("Object");
originalSignature.appendChild(object);
object.appendChild(assertion);
}
public Element createElement( Document doc )
{
Element ele = doc.createElement( Constants.ELEMENT_VARIABLEPARMETER );
ele.setAttribute( Constants.ATTR_VARIABLEPARMETER_NAME, name );
ele.setAttribute( Constants.ATTR_PARMETER_VALUE, stringValue );
ele.setAttribute( Constants.ATTR_PARAMETER_TYPE, getDataType( ) );
return ele;
}
private Element appendEntity(String entity, Document doc) {
Element element=doc.createElement("EntityItem");
String title = entityBroker.getPropertyValue(entity, "title");
element.setAttribute("url", entityBroker.getEntityURL(entity));
element.setAttribute("name",title);
element.setAttribute("size","0");
return element;
}
Document noSuchKey(String id) {
Document doc = this.docBuilder.newDocument();
doc.setXmlVersion("1.0");
Element rootElement = doc.createElement("Error");
rootElement.setAttribute("xmlns", "http://doc.s3.amazonaws.com/2006-03-01");
doc.appendChild(rootElement);
rootElement.appendChild(createElement(doc, "Message", "The resource you requested does not exist"));
rootElement.appendChild(createElement(doc, "Code", "NoSuchKey"));
rootElement.appendChild(createElement(doc, "Resource", id));
return doc;
}
@SuppressWarnings("unused")
public String getQuantity(String traceEPC, String traceTarget, String startTime, String endTime, Long fromTimeMil,
Long toTimeMil, String orderDirection) {
Document doc = createBaseQueryResults(traceEPC, traceTarget, startTime, endTime, orderDirection);
// Time processing
long startTimeMil = 0;
startTimeMil = TimeUtil.getTimeMil(startTime);
ChronoGraph g = Configuration.persistentGraph;
ChronoVertex v = g.getChronoVertex(traceEPC);
TreeSet<Long> timestamps = v.getTimestamps();
Iterator<Long> ti = timestamps.iterator();
Element quantityTrace = doc.createElement("quantityTrace");
while (ti.hasNext()) {
Long t = ti.next();
VertexEvent ve = v.setTimestamp(t);
Object qObj = ve.getProperty("quantity");
Object uObj = ve.getProperty("uom");
Double quantityDouble = null;
if (qObj != null)
quantityDouble = ((BsonDouble) qObj).doubleValue();
String uomString = null;
if (uObj != null)
uomString = ((BsonString) uObj).getValue();
if (quantityDouble != null || uomString != null) {
Element quantity = doc.createElement("quantity");
quantity.setTextContent(quantityDouble.toString());
Element uom = doc.createElement("uom");
uom.setTextContent(uomString);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Element eventTime = doc.createElement("eventTime");
Date date = new Date(t);
String dateString = sdf.format(date);
eventTime.setTextContent(dateString);
Element quantityElement = doc.createElement("quantityElement");
quantityElement.appendChild(eventTime);
quantityElement.appendChild(quantity);
quantityElement.appendChild(uom);
quantityTrace.appendChild(quantityElement);
}
}
Element resultsBody = doc.createElement("resultsBody");
resultsBody.appendChild(quantityTrace);
doc.getFirstChild().appendChild(resultsBody);
return toString(doc);
}
public Node toXML(Document doc) throws DOMException {
Element root = doc.createElement("headerElement");
XML.add(root, "elemName", getName());
XML.addNonNull(root, "elemType", getType());
XML.addNonNull(root, "elemUnit", getUnit());
return root;
}
/**
* 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 = JdkXmlUtils.getDOMDocument();
synchronized (doc)
{
Element element = doc.createElement("token");
Text text = doc.createTextNode(token);
element.appendChild(text);
resultSet.addNode(element);
}
}
return resultSet;
}
/**
* Create an XML element based on a configured range
*
* @param document
* The document the element will be part of
* @param name
* The name to give the new element
* @param range
* The configured range
* @return A configured XML element on the range
*/
private static Element createRangeElement(Document document, String name,
ConfigurableEmitter.Range range) {
Element element = document.createElement(name);
element.setAttribute("min", "" + range.getMin());
element.setAttribute("max", "" + range.getMax());
element.setAttribute("enabled", "" + range.isEnabled());
return element;
}