Java JDOM Element setAttributes() 方法



Java JDOM 的setAttributes() 方法是 Element 类的方法,用于为 XML 元素设置属性列表。如果元素已存在属性,则这些旧属性列表将被此提供的新的属性列表替换。

当传递空列表作为参数时,setAttributes() 方法会删除旧的属性列表。如果列表包含重复的属性,则只有最后一个属性附加到元素。它的行为与对特定属性多次调用 setAttribute() 方法相同,并且只有最后一次调用的属性会被保留。

语法

以下是 Java JDOM Element setAttributes() 方法的语法:

Element.setAttributes(newAttributes);

参数

Java setAttributes() 方法接受一个参数:

newAttributes - 表示需要设置到 XML 元素的属性列表。

返回值

Java setAttributes() 方法在添加属性后返回修改后的 XML 元素。

示例 1

以下是使用 Java JDOM Element setAttributes() 方法的基本示例:

import java.util.ArrayList;
import java.util.List;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class SetAttributes {
   public static void main(String args[]) {
      try {	
    	 //Create Document and add root
	     Document doc = new Document();
	     Element root = new Element("book");
	     doc.setRootElement(root);
	     //Create attributes list
	     Attribute attr1 = new Attribute("type", "single rule");
	     Attribute attr2 = new Attribute("company", "Camlin");
	     List<Attribute> attrList = new ArrayList<Attribute>();
	     attrList.add(attr1);
	     attrList.add(attr2);
	     //Add attribute list to root
	     root.setAttributes(attrList);
	     //Print document
	     XMLOutputter xmlOutput = new XMLOutputter();
	     xmlOutput.setFormat(Format.getPrettyFormat());
	     xmlOutput.output(doc, System.out);	      
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

添加新属性后的 XML 文档将显示。

<?xml version="1.0" encoding="UTF-8"?>
<book type="single rule" company="Camlin" />

示例 2

我们需要解析以下 book.xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<book type="single rule" company="Camlin" />

当传递空列表作为参数时,setAttributes() 方法会清除 XML 元素的属性。

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class SetAttributes {
   public static void main(String args[]) {
      try {	
    	 //Reading the document and get the root
    	 SAXBuilder saxBuilder = new SAXBuilder();
    	 File inputFile = new File("book.xml");
    	 Document doc = saxBuilder.build(inputFile);
    	 Element root = doc.getRootElement();
	     //Create an empty attributes list
	     List<Attribute> attrList = new ArrayList<Attribute>();
	     //Add attribute list to root
	     root.setAttributes(attrList);
	     //Print document
	     XMLOutputter xmlOutput = new XMLOutputter();
	     xmlOutput.setFormat(Format.getPrettyFormat());
	     xmlOutput.output(doc, System.out);	      
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

清除属性后的 XML 文档将显示。

<?xml version="1.0" encoding="UTF-8"?>
<book />
广告
© . All rights reserved.