e535. adding and removing an attribute in a dom element.txt

来自「这里面包含了一百多个JAVA源文件」· 文本 代码 · 共 48 行

TXT
48
字号
If any special characters appear in the value of an attribute (e.g., <>"), they are automatically converted to entities by the XML writers. 
    // Obtain an element; this method is implemented in
    // e510 The Quintessential Program to Create a DOM Document from an XML File
    Document doc = parseXmlFile("infilename.xml", true);
    Element element = doc.getElementById("key1");
    
    // Add an attribute
    element.setAttribute("newAttrName", "attrValue");
    
    // Change the value of an attribute.
    // Special characters are automatically converted to entities by the XML writer.
    element.setAttribute("newAttrName", "<>&\"'");
    
    // Remove an attribute
    element.removeAttribute("value");
    
    // However, if the attribute has a default value, the attribute cannot be removed
    boolean has = element.hasAttribute("value");      // true
    
    // The effect of removing an attribute with a default value
    // is to set the attribute to the default value
    String attrValue = element.getAttribute("value"); // mydefault

This is the sample input for the example: 
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE map [ <!ELEMENT map (entry*) >
                    <!ELEMENT entry EMPTY >
                    <!ATTLIST entry key   ID    #REQUIRED
                                    value CDATA "mydefault"> ]>
    <map>
        <entry key="key1" value="value1"/>
        <entry key="key2" />
    </map>

The resulting XML from running the example is: 
    <?xml version="1.0" encoding="UTF-8"?>
    <map>
        <entry key="key1" newAttrName="&lt;&gt;&amp;&quot;'" value="mydefault"/>
        <entry key="key2" value="mydefault"/>
    </map>

 Related Examples 
e534. Getting and Setting an Attribute in a DOM Element 
e536. Listing All the Attributes of a DOM Element 
e537. Removing All the Attributes in a DOM Element 
e538. Determining If an Attribute Was Supplied in a DOM Element 

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?