e534. getting and setting an attribute in a dom element.txt

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

TXT
46
字号
// Obtain an XML document; this method is implemented in
    // e510 The Quintessential Program to Create a DOM Document from an XML File
    Document doc = parseXmlFile("infilename.xml", false);
    
    // Obtain an element
    Element element = doc.getElementById("key1");
    
    // Determine the presence of an attribute
    boolean has = element.hasAttribute("value");      // true
    
    // Get an attribute value; returns null if not present
    String attrValue = element.getAttribute("value"); // value1
    
    // Change the value of an attribute
    element.setAttribute("value", "newValue1");
    
    // If an attribute is not specified in the XML but has a
    // default value, the attribute is automatically created
    element = doc.getElementById("key2");
    has = element.hasAttribute("value");       // true
    attrValue = element.getAttribute("value"); // value2
    
    // If the attribute value contains special characters,
    // they are automatically converted to entities when the
    // document in dumped
    element.setAttribute("value", "a<\"'&>z");

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" value="newValue1"/>
        <entry key="key2" value="a&lt;&quot;'&amp;&gt;z"/>
    </map>

⌨️ 快捷键说明

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