Java Xml 简明教程

Java DOM Parser - Modify XML Document

Java DOM 解析器 API 提供了修改现有 XML 文档的方法。我们可以使用 Java DOM 解析器的方法来添加或删除元素和属性,修改元素的文本内容和属性值。

setTextContent() 方法替换元素的原始文本,removeAttribute() 删除现有的属性,setAttribute() 方法向元素设置新属性。

Modify XML Using Java DOM Parser

我们可以通过以下步骤使用 DOM 解析器修改 Java 中的 XML 文档。

  1. 步骤 1: 创建 DocumentBuilder 对象

  2. 步骤 2: 读取 XML

  3. 步骤 3: 解析 XML 文稿

  4. *步骤 4:*更新 XML 文档的内容

  5. *步骤 5:*将内容写入 XML 文件

  6. *步骤 6:*输出到控制台进行测试

请参考本节的 this page 了解前三个步骤。

Step4: Updating the content of XML document

我们可以更新现有 XML 文档的文本内容、属性值、添加新元素和新属性。

Element element = xmldoc.getDocumentElement();
element.setTextContent("14");
element.removeAttribute("attr_name");
element.setAttribute("attr_name","attr_value");

setTextContent("text_content") 方法用来设置元素的文本内容。此方法与元素对象一起使用,并以字符串作为参数。

removeAttribute("attr_name") 方法从元素对象中删除属性。如果从中删除属性的元素是只读的,它将引发 NO_MODIFICATION_ALLOWED_ERR 错误。

setAttribute("attr_name","attr_value") 方法以属性名称和属性值作为参数,并将其设置到元素对象。

Updating Text Content

让我们考虑一个包含三个部门详细信息的 college.xml 文件。现在,我们将尝试将电子电气部门的人员数量从 23 更新到 14。 setTextContent("text") 方法用来更新元素的文本内容。

college.xml

以下是更新前的 college.xml 文件。现在让我们尝试在 Java 程序中更新它。

<?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。

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 文档。

<?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) 方法将元素追加到现有文档的根元素。

ModifyXMLAddElementsDemo.java

在以下程序中,我们首先使用 getDocumentElement() 方法获取根元素。然后,我们创建“土木”部门元素并将其添加到根元素。

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”部门后的更新文件如下:

<?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>