下面列出了org.w3c.dom.Attr#setValue ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void appendConformanceClassElement( TestEntry test, Document doc, Element root ) {
if ( test.isConformanceClass() ) {
Element conformanceClass = doc.createElement( "conformanceClass" );
Attr nameAttribute = doc.createAttribute( "name" );
nameAttribute.setValue( test.getLocalName() );
Attr isBasicAttribute = doc.createAttribute( "isBasic" );
isBasicAttribute.setValue( Boolean.toString( test.isBasic() ) );
Attr resultAttribute = doc.createAttribute( "result" );
resultAttribute.setValue( Integer.toString( test.getResult() ) );
conformanceClass.setAttributeNode( nameAttribute );
conformanceClass.setAttributeNode( isBasicAttribute );
conformanceClass.setAttributeNode( resultAttribute );
root.appendChild( conformanceClass );
}
}
/**
* Adds the specified namespace URI to the jaxb:extensionBindingPrefixes
* attribute of the target document.
*/
private void declareExtensionNamespace( Element target, String nsUri ) {
// look for the attribute
Element root = target.getOwnerDocument().getDocumentElement();
Attr att = root.getAttributeNodeNS(Const.JAXB_NSURI,EXTENSION_PREFIXES);
if( att==null ) {
String jaxbPrefix = allocatePrefix(root,Const.JAXB_NSURI);
// no such attribute. Create one.
att = target.getOwnerDocument().createAttributeNS(
Const.JAXB_NSURI,jaxbPrefix+':'+EXTENSION_PREFIXES);
root.setAttributeNodeNS(att);
}
String prefix = allocatePrefix(root,nsUri);
if( att.getValue().indexOf(prefix)==-1 )
// avoid redeclaring the same namespace twice.
att.setValue( att.getValue()+' '+prefix);
}
static void addAttribute(Document document, Node node,
String namespaceUri, String attrName, String attrValue) {
Attr attr;
if (namespaceUri != null) {
attr = document.createAttributeNS(namespaceUri, attrName);
} else {
attr = document.createAttribute(attrName);
}
attr.setValue(attrValue);
if (namespaceUri != null) {
node.getAttributes().setNamedItemNS(attr);
} else {
node.getAttributes().setNamedItem(attr);
}
}
@Test
public void testExclusiveSplitXPathAdvancedWithVars() throws Exception {
KieBase kbase = createKnowledgeBase("BPMN2-ExclusiveSplitXPath-advanced-with-vars.bpmn2");
ksession = createKnowledgeSession(kbase);
ksession.getWorkItemManager().registerWorkItemHandler("Email",
new SystemOutWorkItemHandler());
Map<String, Object> params = new HashMap<String, Object>();
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().newDocument();
Element hi = doc.createElement("hi");
Element ho = doc.createElement("ho");
hi.appendChild(ho);
Attr attr = doc.createAttribute("value");
ho.setAttributeNode(attr);
attr.setValue("a");
params.put("x", hi);
params.put("y", "Second");
ProcessInstance processInstance = ksession.startProcess(
"com.sample.test", params);
assertProcessInstanceCompleted(processInstance);
}
@Test
public void testSetNamedItemNS() throws Exception {
final String nsURI = "urn:BooksAreUs.org:BookInfo";
Document document = createDOMWithNS("NamedNodeMap01.xml");
NodeList nodeList = document.getElementsByTagName("body");
nodeList = nodeList.item(0).getChildNodes();
Node n = nodeList.item(3);
NamedNodeMap namedNodeMap = n.getAttributes();
// creating an Attribute using createAttributeNS
// method having the same namespaceURI
// and the same qualified name as the existing one in the xml file
Attr attr = document.createAttributeNS(nsURI, "b:style");
// setting to a new Value
attr.setValue("newValue");
Node replacedAttr = namedNodeMap.setNamedItemNS(attr); // return the replaced attr
assertEquals(replacedAttr.getNodeValue(), "font-family");
Node updatedAttr = namedNodeMap.getNamedItemNS(nsURI, "style");
assertEquals(updatedAttr.getNodeValue(), "newValue");
// creating a non existing attribute node
attr = document.createAttributeNS(nsURI, "b:newNode");
attr.setValue("newValue");
assertNull(namedNodeMap.setNamedItemNS(attr)); // return null
// checking if the node could be accessed
// using the getNamedItemNS method
Node newAttr = namedNodeMap.getNamedItemNS(nsURI, "newNode");
assertEquals(newAttr.getNodeValue(), "newValue");
}
/**
* Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node.
* @param namespaceURI {@inheritDoc}
* @param localName {@inheritDoc}
* @param value {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeAttribute(String namespaceURI,String localName,String value)throws XMLStreamException {
if(currentNode.getNodeType() == Node.ELEMENT_NODE){
String prefix = null;
if(namespaceURI == null ){
throw new XMLStreamException("NamespaceURI cannot be null");
}
if(localName == null){
throw new XMLStreamException("Local name cannot be null");
}
if(namespaceContext != null){
prefix = namespaceContext.getPrefix(namespaceURI);
}
if(prefix == null){
throw new XMLStreamException("Namespace URI "+namespaceURI +
"is not bound to any prefix" );
}
String qualifiedName = null;
if(prefix.equals("")){
qualifiedName = localName;
}else{
qualifiedName = getQName(prefix,localName);
}
Attr attr = ownerDoc.createAttributeNS(namespaceURI, qualifiedName);
attr.setValue(value);
((Element)currentNode).setAttributeNode(attr);
}else{
//Convert node type to String
throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() +
"and does not allow attributes to be set ");
}
}
protected Element writeBodyElement(Document d) {
Element envelopeElement = d.createElementNS(Constants.SOAP_NS_ENVELOPE, "s:Envelope");
Attr encodingStyleAttr = d.createAttributeNS(Constants.SOAP_NS_ENVELOPE, "s:encodingStyle");
encodingStyleAttr.setValue(Constants.SOAP_URI_ENCODING_STYLE);
envelopeElement.setAttributeNode(encodingStyleAttr);
d.appendChild(envelopeElement);
Element bodyElement = d.createElementNS(Constants.SOAP_NS_ENVELOPE, "s:Body");
envelopeElement.appendChild(bodyElement);
return bodyElement;
}
/**
* Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node.
* @param namespaceURI {@inheritDoc}
* @param localName {@inheritDoc}
* @param value {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeAttribute(String namespaceURI,String localName,String value)throws XMLStreamException {
if(currentNode.getNodeType() == Node.ELEMENT_NODE){
String prefix = null;
if(namespaceURI == null ){
throw new XMLStreamException("NamespaceURI cannot be null");
}
if(localName == null){
throw new XMLStreamException("Local name cannot be null");
}
if(namespaceContext != null){
prefix = namespaceContext.getPrefix(namespaceURI);
}
if(prefix == null){
throw new XMLStreamException("Namespace URI "+namespaceURI +
"is not bound to any prefix" );
}
String qualifiedName = null;
if(prefix.equals("")){
qualifiedName = localName;
}else{
qualifiedName = getQName(prefix,localName);
}
Attr attr = ownerDoc.createAttributeNS(namespaceURI, qualifiedName);
attr.setValue(value);
((Element)currentNode).setAttributeNode(attr);
}else{
//Convert node type to String
throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() +
"and does not allow attributes to be set ");
}
}
/**
* {@inheritDoc}
*/
protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException {
OrganizationDisplayName name = (OrganizationDisplayName) samlObject;
if (name.getName() != null) {
Attr attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), SAMLConstants.XML_NS,
OrganizationDisplayName.LANG_ATTRIB_NAME, SAMLConstants.XML_PREFIX);
attribute.setValue(name.getName().getLanguage());
domElement.setAttributeNodeNS(attribute);
}
}
final String normalizeAttributeValue(String value, Attr attr) {
if (!attr.getSpecified()){
// specified attributes should already have a normalized form
// since those were added by validator
return value;
}
int end = value.length();
// ensure capacity
if (fNormalizedValue.ch.length < end) {
fNormalizedValue.ch = new char[end];
}
fNormalizedValue.length = 0;
boolean normalized = false;
for (int i = 0; i < end; i++) {
char c = value.charAt(i);
if (c==0x0009 || c==0x000A) {
fNormalizedValue.ch[fNormalizedValue.length++] = ' ';
normalized = true;
}
else if(c==0x000D){
normalized = true;
fNormalizedValue.ch[fNormalizedValue.length++] = ' ';
int next = i+1;
if (next < end && value.charAt(next)==0x000A) i=next; // skip following xA
}
else {
fNormalizedValue.ch[fNormalizedValue.length++] = c;
}
}
if (normalized){
value = fNormalizedValue.toString();
attr.setValue(value);
}
return value;
}
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;
}
/**
* Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node.
* @param prefix {@inheritDoc}
* @param namespaceURI {@inheritDoc}
* @param localName {@inheritDoc}
* @param value {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeAttribute(String prefix,String namespaceURI,String localName,String value)throws XMLStreamException {
if(currentNode.getNodeType() == Node.ELEMENT_NODE){
if(namespaceURI == null ){
throw new XMLStreamException("NamespaceURI cannot be null");
}
if(localName == null){
throw new XMLStreamException("Local name cannot be null");
}
if(prefix == null){
throw new XMLStreamException("prefix cannot be null");
}
String qualifiedName = null;
if(prefix.equals("")){
qualifiedName = localName;
}else{
qualifiedName = getQName(prefix,localName);
}
Attr attr = ownerDoc.createAttributeNS(namespaceURI, qualifiedName);
attr.setValue(value);
((Element)currentNode).setAttributeNodeNS(attr);
}else{
//Convert node type to String
throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() +
"and does not allow attributes to be set ");
}
}
/**
* Marshall an attribute name and value to a DOM Element. This is particularly useful for attributes whose names
* appear in namespace-qualified form.
*
* @param attributeName the attribute name in QName form
* @param attributeValue the attribute value
* @param domElement the target element to which to marshall
* @param isIDAttribute flag indicating whether the attribute being marshalled should be handled as an ID-typed
* attribute
*/
public static void marshallAttribute(QName attributeName, String attributeValue, Element domElement,
boolean isIDAttribute) {
Document document = domElement.getOwnerDocument();
Attr attribute = XMLHelper.constructAttribute(document, attributeName);
attribute.setValue(attributeValue);
domElement.setAttributeNodeNS(attribute);
if (isIDAttribute) {
domElement.setIdAttributeNode(attribute, true);
}
}
public void setAttributeNS(String namespaceURI, String qualifiedName,
String value) throws DOMException {
Attr attr = getAttributeNodeNS(namespaceURI, qualifiedName);
if (attr == null) {
attr = document.createAttributeNS(namespaceURI, qualifiedName);
setAttributeNodeNS(attr);
}
attr.setValue(value);
}
/**
* Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node.
* @param namespaceURI {@inheritDoc}
* @param localName {@inheritDoc}
* @param value {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeAttribute(String namespaceURI,String localName,String value)throws XMLStreamException {
if(currentNode.getNodeType() == Node.ELEMENT_NODE){
String prefix = null;
if(namespaceURI == null ){
throw new XMLStreamException("NamespaceURI cannot be null");
}
if(localName == null){
throw new XMLStreamException("Local name cannot be null");
}
if(namespaceContext != null){
prefix = namespaceContext.getPrefix(namespaceURI);
}
if(prefix == null){
throw new XMLStreamException("Namespace URI "+namespaceURI +
"is not bound to any prefix" );
}
String qualifiedName = null;
if(prefix.equals("")){
qualifiedName = localName;
}else{
qualifiedName = getQName(prefix,localName);
}
Attr attr = ownerDoc.createAttributeNS(namespaceURI, qualifiedName);
attr.setValue(value);
((Element)currentNode).setAttributeNode(attr);
}else{
//Convert node type to String
throw new IllegalStateException("Current DOM Node type is "+ currentNode.getNodeType() +
"and does not allow attributes to be set ");
}
}
/**
* The start of an element.
*
* @param element The name of the element.
* @param attributes The element attributes.
* @param augs Additional information that may include infoset augmentations
*
* @exception XNIException
* Thrown by handler to signal an error.
*/
public void startElement(QName element, XMLAttributes attributes, Augmentations augs)
throws XNIException {
Element currentElement = (Element) fCurrentNode;
int attrCount = attributes.getLength();
if (DEBUG_EVENTS) {
System.out.println("==>startElement: " +element+
" attrs.length="+attrCount);
}
for (int i = 0; i < attrCount; i++) {
attributes.getName(i, fAttrQName);
Attr attr = null;
attr = currentElement.getAttributeNodeNS(fAttrQName.uri, fAttrQName.localpart);
AttributePSVI attrPSVI =
(AttributePSVI) attributes.getAugmentations(i).getItem(Constants.ATTRIBUTE_PSVI);
if (attrPSVI != null) {
//REVISIT: instead we should be using augmentations:
// to set/retrieve Id attributes
XSTypeDefinition decl = attrPSVI.getMemberTypeDefinition();
boolean id = false;
if (decl != null){
id = ((XSSimpleType)decl).isIDType();
} else{
decl = attrPSVI.getTypeDefinition();
if (decl !=null){
id = ((XSSimpleType)decl).isIDType();
}
}
if (id){
((ElementImpl)currentElement).setIdAttributeNode(attr, true);
}
if (fPSVI) {
((PSVIAttrNSImpl) attr).setPSVI(attrPSVI);
}
if ((fConfiguration.features & DOMConfigurationImpl.DTNORMALIZATION) != 0) {
// datatype-normalization
// NOTE: The specified value MUST be set after we set
// the node value because that turns the "specified"
// flag to "true" which may overwrite a "false"
// value from the attribute list.
boolean specified = attr.getSpecified();
attr.setValue(attrPSVI.getSchemaNormalizedValue());
if (!specified) {
((AttrImpl) attr).setSpecified(specified);
}
}
}
}
}
/**
* The start of an element.
*
* @param element The name of the element.
* @param attributes The element attributes.
* @param augs Additional information that may include infoset augmentations
*
* @exception XNIException
* Thrown by handler to signal an error.
*/
public void startElement(QName element, XMLAttributes attributes, Augmentations augs)
throws XNIException {
Element currentElement = (Element) fCurrentNode;
int attrCount = attributes.getLength();
if (DEBUG_EVENTS) {
System.out.println("==>startElement: " +element+
" attrs.length="+attrCount);
}
for (int i = 0; i < attrCount; i++) {
attributes.getName(i, fAttrQName);
Attr attr = null;
attr = currentElement.getAttributeNodeNS(fAttrQName.uri, fAttrQName.localpart);
AttributePSVI attrPSVI =
(AttributePSVI) attributes.getAugmentations(i).getItem(Constants.ATTRIBUTE_PSVI);
if (attrPSVI != null) {
//REVISIT: instead we should be using augmentations:
// to set/retrieve Id attributes
XSTypeDefinition decl = attrPSVI.getMemberTypeDefinition();
boolean id = false;
if (decl != null){
id = ((XSSimpleType)decl).isIDType();
} else{
decl = attrPSVI.getTypeDefinition();
if (decl !=null){
id = ((XSSimpleType)decl).isIDType();
}
}
if (id){
((ElementImpl)currentElement).setIdAttributeNode(attr, true);
}
if (fPSVI) {
((PSVIAttrNSImpl) attr).setPSVI(attrPSVI);
}
if ((fConfiguration.features & DOMConfigurationImpl.DTNORMALIZATION) != 0) {
// datatype-normalization
// NOTE: The specified value MUST be set after we set
// the node value because that turns the "specified"
// flag to "true" which may overwrite a "false"
// value from the attribute list.
boolean specified = attr.getSpecified();
attr.setValue(attrPSVI.getSchemaNormalizedValue());
if (!specified) {
((AttrImpl) attr).setSpecified(specified);
}
}
}
}
}
private void saveMap(TileManager tm) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("map");
Attr width = doc.createAttribute("width");
width.setValue(Integer.toString(tm.getChunkSize()));
rootElement.setAttributeNode(width);
Attr height = doc.createAttribute("height");
height.setValue(Integer.toString(tm.getChunkSize()));
rootElement.setAttributeNode(height);
Attr tilewidth = doc.createAttribute("tilewidth");
tilewidth.setValue(Integer.toString(tm.getBlockWidth()));
rootElement.setAttributeNode(tilewidth);
Attr tileheight = doc.createAttribute("tileheight");
tileheight.setValue(Integer.toString(tm.getBlockHeight()));
rootElement.setAttributeNode(tileheight);
doc.appendChild(rootElement);
Element tileset = doc.createElement("tileset");
Attr name = doc.createAttribute("name");
name.setValue(tm.getFilename());
tileset.setAttributeNode(name);
Attr columns = doc.createAttribute("columns");
columns.setValue(Integer.toString(tm.getColumns()));
tileset.setAttributeNode(columns);
tileset.setAttributeNode(tilewidth);
tileset.setAttributeNode(tileheight);
rootElement.appendChild(tileset);
// create function for layers?
Element solid = doc.createElement("data");
Attr nameSolid = doc.createAttribute("name");
nameSolid.setValue("Solid");
solid.setAttributeNode(nameSolid);
solid.setAttributeNode(width);
solid.setAttributeNode(height);
Element data = doc.createElement("data");
data.appendChild(doc.createTextNode(tm.getSolid()));
solid.appendChild(data);
rootElement.appendChild(solid);
Element layer1 = doc.createElement("data");
Attr nameLayer1 = doc.createAttribute("name");
nameLayer1.setValue("Layer1");
layer1.setAttributeNode(nameLayer1);
layer1.setAttributeNode(width);
layer1.setAttributeNode(height);
Element data1 = doc.createElement("data");
data1.appendChild(doc.createTextNode(tm.getGenMap()));
layer1.appendChild(data1);
rootElement.appendChild(layer1);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:\\file.xml"));
transformer.transform(source, result);
System.out.println("Map saved!");
} catch (Exception e) {
e.printStackTrace();
}
}
protected Node cloneNode(Document doc, boolean deep) {
Attr attr = doc.createAttributeNS(getNamespaceURI(), getLocalName());
attr.setValue(getValue());
attr.setPrefix(getPrefix());
return attr;
}
/**
* 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);
}