Java Xml 简明教程
Java DOM Parser - Modify XML Document
Java DOM 解析器 API 提供了修改现有 XML 文档的方法。我们可以使用 Java DOM 解析器的方法来添加或删除元素和属性,修改元素的文本内容和属性值。
Java DOM parser API provides methods to modify the already existing XML documents. We can add or remove elements and attributes, modify the text content of elements and attribute values using the methods of Java DOM parser.
setTextContent() 方法替换元素的原始文本,removeAttribute() 删除现有的属性,setAttribute() 方法向元素设置新属性。
The setTextContent() method replaces the original text of elements, removeAttribute() removes the existing attributes and the setAttribute() method sets the new attributes to elements.
Modify XML Using Java DOM Parser
我们可以通过以下步骤使用 DOM 解析器修改 Java 中的 XML 文档。
We can modify an XML document in java using DOM parser through following steps.
-
*Step 1: *Creating a DocumentBuilder Object
-
*Step 2: *Reading the XML
-
*Step 3: *Parsing the XML Document
-
*Step 4: *Updating the content of XML document
-
*Step 5: *Writing the content into XML file
-
*Step 6: *Output to console for testing
请参考本节的 this page 了解前三个步骤。
Refer this page of this section for first three steps.
Step4: Updating the content of XML document
我们可以更新现有 XML 文档的文本内容、属性值、添加新元素和新属性。
We can update text content, attribute values, add new elements and new attributes to our existing XML documents.
Element element = xmldoc.getDocumentElement();
element.setTextContent("14");
element.removeAttribute("attr_name");
element.setAttribute("attr_name","attr_value");
setTextContent("text_content") 方法用来设置元素的文本内容。此方法与元素对象一起使用,并以字符串作为参数。
The setTextContent("text_content") method is used to set the text content of an Element. This method is used with the Element object and takes String as an argument.
removeAttribute("attr_name") 方法从元素对象中删除属性。如果从中删除属性的元素是只读的,它将引发 NO_MODIFICATION_ALLOWED_ERR 错误。
The removeAttribute("attr_name") method removes the attribute from the Element object. It throws NO_MODIFICATION_ALLOWED_ERR error if the Element from which we want to remove the attribute is readonly.
setAttribute("attr_name","attr_value") 方法以属性名称和属性值作为参数,并将其设置到元素对象。
The setAttribute("attr_name","attr_value") method takes attribute name and attribute value as arguments and sets it to the Element object.
Updating Text Content
让我们考虑一个包含三个部门详细信息的 college.xml 文件。现在,我们将尝试将电子电气部门的人员数量从 23 更新到 14。 setTextContent("text") 方法用来更新元素的文本内容。
Let us consider college.xml file where we have three department details. Now, we will try to update staff count for Electrical and Electronics department from 23 to 14. The method setTextContent("text") is used to update the text content of an element.
college.xml
以下是更新前的 college.xml 文件。现在让我们尝试在 Java 程序中更新它。
Following is the college.xml file before updating. Now let us try to update this in our java program.
<?xml version="1.0" encoding="UTF-8" standalone="no"?><college>
<department id="101">
<name>Computer Science</name>
<staffCount>20</staffCount>
</department>
<department id="102">
<name>Electrical and Electronics</name>
<staffCount>23</staffCount>
</department>
<department id="103">
<name>Mechanical</name>
<staffCount>15</staffCount>
</department>
</college>
ModifyXMLDemo.java
在以下 Java 程序中,我们将所有标记名称为“department”的节点检索到一个 NodeList 中。然后,我们迭代所有节点以查找“电子电气”部门,并将 staffCount 属性更改为 14。
In the following java program, we retrieved all the nodes with tag name, "department" into a NodeList. Then, we iterated all the nodes to find "Electrical and Electronics" department and changed the staffCount attribute to 14.
import java.io.File;
import java.io.FileOutputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class ModifyXMLDemo {
public static void main(String argv[]) {
try {
//Creating a DocumentBuilder Object
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
//Reading the XML file
File inputFile = new File("src/modifydom.xml");
//Parsing the XML Document
Document doc = docBuilder.parse(inputFile);
//Updating the staffCount for "Electrical and Electronics" department
NodeList deptList=doc.getElementsByTagName("department");
for(int i=0;i<deptList.getLength();i++)
{
Element element= (Element) (deptList.item(i));
String s=element.getElementsByTagName("name").item(0).getTextContent();
if(s.equals("Electrical and Electronics"))
{
Element staffCount = (Element) element.getElementsByTagName("staffCount").item(0);
staffCount.setTextContent("14");
}
}
//Writing the updated content into the file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
FileOutputStream output = new FileOutputStream("college.xml");
StreamResult result = new StreamResult(output);
transformer.transform(source, result);
//writing the content on console
StreamResult consoleResult = new StreamResult(System.out);
transformer.transform(source, consoleResult);
} catch (Exception e) { e.printStackTrace();}
}
}
Output
以下是更新 staffCount 后的更新 XML 文档。
Following is the updated XML document after updating staffCount.
<?xml version="1.0" encoding="UTF-8" standalone="no"?><college>
<department id="101">
<name>Computer Science</name>
<staffCount>20</staffCount>
</department>
<department id="102">
<name>Electrical and Electronics</name>
<staffCount>14</staffCount>
</department>
<department id="103">
<name>Mechanical</name>
<staffCount>15</staffCount>
</department>
</college>
Adding New Elements
现在,让我们更进一步,尝试在上述“college.xml”文件中添加一个名为“土木”的新部门。要添加新元素,我们可以使用 createElement("Element_name") 方法进行创建,并 appendChild(Element) 方法将元素追加到现有文档的根元素。
Now, let us go a bit further and try to add one more department named "Civil" to our above "college.xml" file. To add new elements, we can use createElement("Element_name") method to create and appendChild(Element) to append the element to the existing document’s root element.
ModifyXMLAddElementsDemo.java
在以下程序中,我们首先使用 getDocumentElement() 方法获取根元素。然后,我们创建“土木”部门元素并将其添加到根元素。
In the following program, we first got the root element by using getDocumentElement() method. Then, we created "Civil" department element and added to the root element.
import java.io.File;
import java.io.FileOutputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class ModifyXMLAddElementsDemo {
public static void main(String argv[]) {
try {
//Creating a DocumentBuilder Object
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
//Reading the XML file
File inputFile = new File("college.xml");
//Parsing the XML Document
Document doc = docBuilder.parse(inputFile);
//Adding new department element
Element rootElement = doc.getDocumentElement();
Element department = doc.createElement("department");
department.setAttribute("id", "104");
Element name = doc.createElement("name");
Element staffCount = doc.createElement("staffCount");
department.appendChild(name);
department.appendChild(staffCount);
name.appendChild(doc.createTextNode("Civil"));
staffCount.appendChild(doc.createTextNode("10"));
rootElement.appendChild(department);
//Creating transformer object
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
//Writing updated content into the file
DOMSource source = new DOMSource(doc);
FileOutputStream output = new FileOutputStream("college.xml");
StreamResult result = new StreamResult(output);
transformer.transform(source, result);
//writing the content on console
StreamResult consoleResult = new StreamResult(System.out);
transformer.transform(source, consoleResult);
} catch (Exception e) { e.printStackTrace();}
}
}
Output
添加“Civil”部门后的更新文件如下:
The updated file after adding "Civil" department is as follows :
<?xml version="1.0" encoding="UTF-8" standalone="no"?><college>
<department id="101">
<name>Computer Science</name>
<staffCount>20</staffCount>
</department>
<department id="102">
<name>Electrical and Electronics</name>
<staffCount>14</staffCount>
</department>
<department id="103">
<name>Mechanical</name>
<staffCount>15</staffCount>
</department>
<department id="104"><name>Civil</name><staffCount>10</staffCount></department></college>