下面列出了org.w3c.dom.Document#createAttribute ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Export to xml document
*
* @param doc xml document
* @param parent parent xml element
*/
@Override
public void exportToXML(Document doc, Element parent) {
Element brk = doc.createElement("Break");
Attr captionAttr = doc.createAttribute("Caption");
Attr startValueAttr = doc.createAttribute("StartValue");
Attr endValueAttr = doc.createAttribute("EndValue");
Attr colorAttr = doc.createAttribute("Color");
Attr isNoDataAttr = doc.createAttribute("IsNoData");
captionAttr.setValue(this.getCaption());
startValueAttr.setValue(String.valueOf(this.getStartValue()));
endValueAttr.setValue(String.valueOf(this.getEndValue()));
colorAttr.setValue(ColorUtil.toHexEncoding(this.getColor()));
isNoDataAttr.setValue(String.valueOf(this.isNoData()));
brk.setAttributeNode(captionAttr);
brk.setAttributeNode(startValueAttr);
brk.setAttributeNode(endValueAttr);
brk.setAttributeNode(colorAttr);
brk.setAttributeNode(isNoDataAttr);
parent.appendChild(brk);
}
/**
* Update the namespace of a given node to work with a given document.
*
* @param node the node to update
* @param document the new document
*
* @return false if the attribute is to be dropped
*/
private static boolean processSingleNodeNamespace(Node node, Document document) {
if ("xmlns".equals(node.getLocalName())) {
return false;
}
String ns = node.getNamespaceURI();
if (ns != null) {
NamedNodeMap docAttributes = document.getAttributes();
String prefix = getPrefixForNs(docAttributes, ns);
if (prefix == null) {
prefix = getUniqueNsAttribute(docAttributes);
Attr nsAttr = document.createAttribute(prefix);
nsAttr.setValue(ns);
document.getChildNodes().item(0).getAttributes().setNamedItem(nsAttr);
}
// set the prefix on the node, by removing the xmlns: start
prefix = prefix.substring(6);
node.setPrefix(prefix);
}
return true;
}
/**
* Adds a property
*
* @param name: Name of property
* @param value: Value
* @param doc: Document
* @param parent: Parent element of the property to be added as a child
*/
private static void addProperty(String name, String value, Document doc, Element parent, boolean encrypted) {
Element property = doc.createElement("Property");
Attr attr;
if (encrypted) {
attr = doc.createAttribute("encrypted");
attr.setValue("true");
property.setAttributeNode(attr);
}
attr = doc.createAttribute("name");
attr.setValue(name);
property.setAttributeNode(attr);
property.setTextContent(value);
parent.appendChild(property);
}
private static Document getDocument(UserStoreDTO userStoreDTO, boolean editSecondaryUserStore,
DocumentBuilder documentBuilder, String existingDomainName)
throws IdentityUserStoreMgtException {
Document doc = documentBuilder.newDocument();
//create UserStoreManager element
Element userStoreElement = doc.createElement(UserCoreConstants.RealmConfig.LOCAL_NAME_USER_STORE_MANAGER);
doc.appendChild(userStoreElement);
Attr attrClass = doc.createAttribute("class");
if (userStoreDTO != null) {
attrClass.setValue(userStoreDTO.getClassName());
userStoreElement.setAttributeNode(attrClass);
if (userStoreDTO.getClassName() != null) {
addProperties(existingDomainName, userStoreDTO.getClassName(), userStoreDTO.getProperties(),
doc, userStoreElement, editSecondaryUserStore);
}
addProperty(UserStoreConfigConstants.DOMAIN_NAME, userStoreDTO.getDomainId(), doc, userStoreElement, false);
addProperty(UserStoreConfigurationConstant.DESCRIPTION, userStoreDTO.getDescription(), doc,
userStoreElement, false);
}
return doc;
}
private static void visitNode(Node node, HashMap<String, Integer> instances) {
Document doc = node.getOwnerDocument();
NamedNodeMap attributes = node.getAttributes();
String androidClass;
try {
androidClass = attributes.getNamedItem("class").getNodeValue();
} catch (Exception e) {
return;
}
androidClass = cleanTagName(androidClass);
if (!instances.containsKey(androidClass)) {
instances.put(androidClass, 0);
}
Integer instance = instances.get(androidClass);
Node attrNode = doc.createAttribute("instance");
attrNode.setNodeValue(instance.toString());
attributes.setNamedItem(attrNode);
doc.renameNode(node, node.getNamespaceURI(), androidClass);
instances.put(androidClass, instance + 1);
}
private void appendEndTestElement( TestEntry test, Document doc, Element root ) {
Element endtest = doc.createElement( "endtest" );
Attr resultAttribute = doc.createAttribute( "result" );
resultAttribute.setValue( Integer.toString( test.getResult() ) );
endtest.setAttributeNode( resultAttribute );
root.appendChild( endtest );
}
public static void putAt(Element self, String property, Object value) {
if (property.startsWith("@")) {
String attributeName = property.substring(1);
Document doc = self.getOwnerDocument();
Attr newAttr = doc.createAttribute(attributeName);
newAttr.setValue(value.toString());
self.setAttributeNode(newAttr);
return;
}
InvokerHelper.setProperty(self, property, value);
}
static Node duplicateNode(Document document, Node node) {
Node newNode;
if (node.getNamespaceURI() != null) {
newNode = document.createElementNS(node.getNamespaceURI(), node.getLocalName());
} else {
newNode = document.createElement(node.getNodeName());
}
// copy the attributes
NamedNodeMap attributes = node.getAttributes();
for (int i = 0 ; i < attributes.getLength(); i++) {
Attr attr = (Attr) attributes.item(i);
Attr newAttr;
if (attr.getNamespaceURI() != null) {
newAttr = document.createAttributeNS(attr.getNamespaceURI(), attr.getLocalName());
newNode.getAttributes().setNamedItemNS(newAttr);
} else {
newAttr = document.createAttribute(attr.getName());
newNode.getAttributes().setNamedItem(newAttr);
}
newAttr.setValue(attr.getValue());
}
// then duplicate the sub-nodes.
NodeList children = node.getChildNodes();
for (int i = 0 ; i < children.getLength() ; i++) {
Node child = children.item(i);
if (child.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
Node duplicatedChild = duplicateNode(document, child);
newNode.appendChild(duplicatedChild);
}
return newNode;
}
private Element buildString(Document document, String key, String stringValue) {
Element string = document.createElement("string");
Attr name = document.createAttribute("name");
name.setValue(key);
string.setAttributeNode(name);
Text value = document.createTextNode(stringValue);
string.appendChild(value);
return string;
}
private static void saveCollections(TGBrowserManager manager, Document document){
//chords tag
Node listNode = document.createElement(ITEM_LIST_TAG);
Iterator<TGBrowserCollection> collections = manager.getCollections();
while(collections.hasNext()){
TGBrowserCollection collection = (TGBrowserCollection)collections.next();
//collection tag
Node node = document.createElement(ITEM_TAG);
listNode.appendChild(node);
//type attribute
Attr typeAttr = document.createAttribute(ATTRIBUTE_TYPE);
typeAttr.setNodeValue(collection.getType());
//title attribute
Attr titleAttr = document.createAttribute(ATTRIBUTE_TITLE);
titleAttr.setNodeValue(collection.getData().getTitle());
//data attribute
Attr dataAttr = document.createAttribute(ATTRIBUTE_DATA);
dataAttr.setNodeValue(collection.getData().getData());
node.getAttributes().setNamedItem(typeAttr);
node.getAttributes().setNamedItem(titleAttr);
node.getAttributes().setNamedItem(dataAttr);
}
document.appendChild(listNode);
}
@Test
public void testSetAttributeNode() throws Exception {
final String attrName = "myAttr";
final String attrValue = "attrValue";
Document document = createDOM("ElementSample02.xml");
Element elemNode = document.createElement("pricetag2");
Attr myAttr = document.createAttribute(attrName);
myAttr.setValue(attrValue);
assertNull(elemNode.setAttributeNode(myAttr));
assertEquals(elemNode.getAttribute(attrName), attrValue);
}
public static void addAttribute(Document doc, String name, Element e, String value)
{
Node attrNode = doc.createAttribute(name);
attrNode.setNodeValue(value);
NamedNodeMap attrs = e.getAttributes();
attrs.setNamedItem(attrNode);
}
private static Element writeGridItemInformation(Document doc, Element rootElement, GridColumn[] columnsList,
DataVisualizer dataVisualizer, GridItem item)
{
Element rowElement = doc.createElement(ROW_TAG);
rootElement.appendChild(rowElement);
// Attr rowNumber = doc.createAttribute("id");
// rowNumber.setValue(Integer.toString(item.getRowIndex()));
// rowElement.setAttributeNode(rowNumber);
for (int column = 0; column < columnsList.length; column++)
{
String text = dataVisualizer.getText(item, column);
if (text != null)
{
Element columnElement = doc.createElement(COLUMN_TAG);
columnElement.appendChild(doc.createTextNode(text));
rowElement.appendChild(columnElement);
Attr columnNumber = doc.createAttribute(ID_TAG);
columnNumber.setValue(Integer.toString(column));
columnElement.setAttributeNode(columnNumber);
}
}
return rowElement;
}
@Test
public void testSetValue() throws Exception {
Document document = createDOM("Attr01.xml");
Attr attr = document.createAttribute("newAttribute");
attr.setValue("newVal");
assertEquals(attr.getValue(), "newVal");
}
/**
* Generates the resource files
*/
public void generate() throws IOException, ParserConfigurationException {
File pkgFolder = getFolderPath();
if (!pkgFolder.isDirectory()) {
if (!pkgFolder.mkdirs()) {
throw new RuntimeException("Failed to create " + pkgFolder.getAbsolutePath());
}
}
File resFile = new File(pkgFolder, RES_VALUE_FILENAME_XML);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(false);
factory.setIgnoringComments(true);
DocumentBuilder builder;
builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Node rootNode = document.createElement(TAG_RESOURCES);
document.appendChild(rootNode);
rootNode.appendChild(document.createTextNode("\n"));
rootNode.appendChild(document.createComment("Automatically generated file. DO NOT MODIFY"));
rootNode.appendChild(document.createTextNode("\n\n"));
for (Object item : mItems) {
if (item instanceof ClassField) {
ClassField field = (ClassField)item;
ResourceType type = ResourceType.getEnum(field.getType());
boolean hasResourceTag = (type != null && RESOURCES_WITH_TAGS.contains(type));
Node itemNode = document.createElement(hasResourceTag ? field.getType() : TAG_ITEM);
Attr nameAttr = document.createAttribute(ATTR_NAME);
nameAttr.setValue(field.getName());
itemNode.getAttributes().setNamedItem(nameAttr);
if (!hasResourceTag) {
Attr typeAttr = document.createAttribute(ATTR_TYPE);
typeAttr.setValue(field.getType());
itemNode.getAttributes().setNamedItem(typeAttr);
}
if (type == ResourceType.STRING) {
Attr translatable = document.createAttribute(ATTR_TRANSLATABLE);
translatable.setValue(VALUE_FALSE);
itemNode.getAttributes().setNamedItem(translatable);
}
if (!field.getValue().isEmpty()) {
itemNode.appendChild(document.createTextNode(field.getValue()));
}
rootNode.appendChild(itemNode);
} else if (item instanceof String) {
rootNode.appendChild(document.createTextNode("\n"));
rootNode.appendChild(document.createComment((String) item));
rootNode.appendChild(document.createTextNode("\n"));
}
}
String content;
try {
content = XmlPrettyPrinter.prettyPrint(document, true);
} catch (Throwable t) {
content = XmlUtils.toXml(document);
}
Files.write(content, resFile, Charsets.UTF_8);
}
/**
* This method export a grid into a outputstream using xml.
* SWT Main thread is required for the export.
* Full supports for Grid Table.
* Grid Tree only visible items was exported.
*
* @param grid the grid who will be export to xml.
* @param outputStream used for the export.
* @throws ParserConfigurationException
* @throws TransformerException
*/
public static void gridToXml(Grid grid, OutputStream outputStream) throws ParserConfigurationException,
TransformerException
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
final Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement(GRID_TAG);
doc.appendChild(rootElement);
GridColumn[] columnsArray = grid.getColumns();
Element header = doc.createElement(HEADER_TAG);
rootElement.appendChild(header);
for (int column = 0; column < columnsArray.length; column++)
{
Element columnElement = doc.createElement(COLUMN_TAG);
columnElement.appendChild(doc.createTextNode(columnsArray[column].getText()));
header.appendChild(columnElement);
Attr columnNumber = doc.createAttribute(ID_TAG);
columnNumber.setValue(Integer.toString(column));
columnElement.setAttributeNode(columnNumber);
}
GridItem[] itemsList = grid.getItems();
DataVisualizer dataVisualizer = grid.getDataVisualizer();
Element rowsElement = doc.createElement(ROWS_TAG);
rootElement.appendChild(rowsElement);
writeChildren(doc, rowsElement, columnsArray, itemsList, dataVisualizer, 0);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, INDENT_ACCEPTED_VALUE);
transformer.setOutputProperty(INDET_PROPERTY, INDENT_VALUE);
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(outputStream);
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
}
/**
* Helper method used by {@link #findAlternateToolsXml(InputStream)} to duplicate a node
* and attach it to the given root in the new document.
*/
private Element duplicateNode(Element newRootNode, Element oldNode,
String namespaceUri, String prefix) {
// The implementation here is more or less equivalent to
//
// newRoot.appendChild(newDoc.importNode(oldNode, deep=true))
//
// except we can't just use importNode() since we need to deal with the fact
// that the old document is not namespace-aware yet the new one is.
Document newDoc = newRootNode.getOwnerDocument();
Element newNode = null;
String nodeName = oldNode.getNodeName();
int pos = nodeName.indexOf(':');
if (pos > 0 && pos < nodeName.length() - 1) {
nodeName = nodeName.substring(pos + 1);
newNode = newDoc.createElementNS(namespaceUri, nodeName);
newNode.setPrefix(prefix);
} else {
newNode = newDoc.createElement(nodeName);
}
newRootNode.appendChild(newNode);
// Merge in all the attributes
NamedNodeMap attrs = oldNode.getAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
Attr attr = (Attr) attrs.item(i);
Attr newAttr = null;
String attrName = attr.getNodeName();
pos = attrName.indexOf(':');
if (pos > 0 && pos < attrName.length() - 1) {
attrName = attrName.substring(pos + 1);
newAttr = newDoc.createAttributeNS(namespaceUri, attrName);
newAttr.setPrefix(prefix);
} else {
newAttr = newDoc.createAttribute(attrName);
}
newAttr.setNodeValue(attr.getNodeValue());
if (pos > 0) {
newNode.getAttributes().setNamedItemNS(newAttr);
} else {
newNode.getAttributes().setNamedItem(newAttr);
}
}
// Merge all child elements and texts
for (Node child = oldNode.getFirstChild(); child != null; child = child.getNextSibling()) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
duplicateNode(newNode, (Element) child, namespaceUri, prefix);
} else if (child.getNodeType() == Node.TEXT_NODE) {
Text newText = newDoc.createTextNode(child.getNodeValue());
newNode.appendChild(newText);
}
}
return newNode;
}
private void addLayoutNorthArrowElement(Document doc, Element parent, LayoutNorthArrow aNorthArrow) {
Element northArrow = doc.createElement("LayoutNorthArrow");
Attr elementType = doc.createAttribute("ElementType");
Attr layoutMapIndex = doc.createAttribute("LayoutMapIndex");
Attr BackColor = doc.createAttribute("BackColor");
Attr foreColor = doc.createAttribute("ForeColor");
Attr DrawNeatLine = doc.createAttribute("DrawNeatLine");
Attr NeatLineColor = doc.createAttribute("NeatLineColor");
Attr NeatLineSize = doc.createAttribute("NeatLineSize");
Attr Left = doc.createAttribute("Left");
Attr Top = doc.createAttribute("Top");
Attr Width = doc.createAttribute("Width");
Attr Height = doc.createAttribute("Height");
Attr angle = doc.createAttribute("Angle");
Attr drawBackColor = doc.createAttribute("DrawBackColor");
elementType.setValue(aNorthArrow.getElementType().toString());
layoutMapIndex.setValue(String.valueOf(getLayoutMapIndex(aNorthArrow.getLayoutMap())));
BackColor.setValue(ColorUtil.toHexEncoding(aNorthArrow.getBackColor()));
foreColor.setValue(ColorUtil.toHexEncoding(aNorthArrow.getForeColor()));
DrawNeatLine.setValue(String.valueOf(aNorthArrow.isDrawNeatLine()));
NeatLineColor.setValue(ColorUtil.toHexEncoding(aNorthArrow.getNeatLineColor()));
NeatLineSize.setValue(String.valueOf(aNorthArrow.getNeatLineSize()));
Left.setValue(String.valueOf(aNorthArrow.getLeft()));
Top.setValue(String.valueOf(aNorthArrow.getTop()));
Width.setValue(String.valueOf(aNorthArrow.getWidth()));
Height.setValue(String.valueOf(aNorthArrow.getHeight()));
angle.setValue(String.valueOf(aNorthArrow.getAngle()));
drawBackColor.setValue(String.valueOf(aNorthArrow.isDrawBackColor()));
northArrow.setAttributeNode(elementType);
northArrow.setAttributeNode(layoutMapIndex);
northArrow.setAttributeNode(BackColor);
northArrow.setAttributeNode(foreColor);
northArrow.setAttributeNode(DrawNeatLine);
northArrow.setAttributeNode(NeatLineColor);
northArrow.setAttributeNode(NeatLineSize);
northArrow.setAttributeNode(Left);
northArrow.setAttributeNode(Top);
northArrow.setAttributeNode(Width);
northArrow.setAttributeNode(Height);
northArrow.setAttributeNode(angle);
northArrow.setAttributeNode(drawBackColor);
parent.appendChild(northArrow);
}
/**
* Save project file
*
* @param aFile File name
* @throws javax.xml.parsers.ParserConfigurationException
*/
public void saveProjFile(String aFile) throws ParserConfigurationException {
_fileName = aFile;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element root = doc.createElement("MeteoInfo");
File af = new File(aFile);
Attr fn = doc.createAttribute("File");
Attr type = doc.createAttribute("Type");
fn.setValue(af.getName());
type.setValue("projectfile");
root.setAttributeNode(fn);
root.setAttributeNode(type);
doc.appendChild(root);
//Add language element
//addLanguageElement(doc, root, Thread.CurrentThread.CurrentUICulture.Name);
//Add LayersLegend content
_mainForm.getMapDocument().getMapLayout().updateMapFrameOrder();
_mainForm.getMapDocument().exportProjectXML(doc, root, _fileName);
//Add MapLayout content
_mainForm.getMapDocument().getMapLayout().exportProjectXML(doc, root);
//Save project file
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(doc);
Properties properties = transformer.getOutputProperties();
properties.setProperty(OutputKeys.ENCODING, "UTF-8");
properties.setProperty(OutputKeys.INDENT, "yes");
properties.setProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.setOutputProperties(properties);
// transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
// transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
//PrintWriter pw = new PrintWriter(new FileOutputStream(aFile));
FileOutputStream out = new FileOutputStream(aFile);
StreamResult result = new StreamResult(out);
transformer.transform(source, result);
} catch (TransformerException mye) {
} catch (IOException exp) {
}
}
/**
* This method adds the page help content in the template xml file created by createXmlFile() method of this class
*
* @param pageHelpContent help content of the page
* @param pageId the page id
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
* @throws TransformerException
*/
public void addHelpContentToXmlFile(final String pageHelpContent, final int pageId) throws ParserConfigurationException, SAXException, IOException, TransformerException {
final File xmlFile = Utils.getResourceFromWithin(getFilePath());
final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
final Document doc = docBuilder.parse(xmlFile);
// gets the root element contexts
final Node contexts = doc.getElementsByTagName(Constants.contextsElement).item(0);
final Element context = doc.createElement(Constants.contextElement);
contexts.appendChild(context);
// value of id attribute
final String idValue = getTaskName() + "_Page" + pageId;
// creates the id attribute of context element
final Attr idAttribute = doc.createAttribute(Constants.idAttribute);
idAttribute.setValue(idValue);
context.setAttributeNode(idAttribute);
// creates the title attribute of context element
final Attr titleAttribute = doc.createAttribute(Constants.titleAttribute);
titleAttribute.setValue(Constants.titleAttributeValue);
context.setAttributeNode(titleAttribute);
// Creates the description element which will contain the help content of the page
final Element description = doc.createElement(Constants.descriptionAttribute);
description.appendChild(doc.createTextNode(pageHelpContent));
context.appendChild(description);
// writes the content in to xml file
final TransformerFactory transformerFactory = TransformerFactory.newInstance();
final Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
final DOMSource source = new DOMSource(doc);
final StreamResult result = new StreamResult(xmlFile);
transformer.transform(source, result);
}