Java Xml 简明教程
Java SAX Parser - Modify XML Document
Java SAX解析器是一种Java API,可用于解析和修改XML文档。要使用SAX解析器修改任何XML文档,我们必须将数据存储在任何数据结构中,因为我们无法返回,因为它只有向前只读访问权限。在本章中,我们将详细了解如何读取和修改现有XML文档。
Java SAX parser is a Java API that can be used to parse and modify XML documents. To modify any XML document using SAX parser, We have to store the data in any data structure because we cannot go back as it has only forward read-only access. In this chapter, we are going to see how to read and modify existing XML document in detail.
Modify XML Using Java SAX Parser
-
*Step 1: *Implementing a Handler class
-
*Step 2: *Creating a SAXParser Object
-
*Step 3: *Reading the XML
-
*Step 4: *Creating object for Handler class
-
*Step 5: *Parsing the XML Document
-
*Step 6: *Writing the updated content into file
有关前五个步骤,请参阅本部分的 Parse XML Document 章。
Refer Parse XML Document chapter of this section for the first five steps.
Modifying XML File
SAX解析器不会像DOM那样提供对元素的随机访问。我们可以在实现DefaultHandler的Handler类中实现回调方法,以创建并向已存在的XML文档添加新元素。
SAX parser will not provide random access to elements as DOM provides. We can implement the call back methods in Handler class that implements DefaultHandler to create and add new elements to the already exisiting XML document.
Example
在此示例中,我们将了解如何通过将结果元素添加到学生元素来修改studentData.xml文件。以下是需要通过在</marks>标记的末尾附加<Result>Pass<Result/>来修改的 sudentData.xml 文件。
In this example, we are going to see how to modify studentData.xml file by adding result element to the student element. Here is the sudentData.xml file that we need to modify by appending <Result>Pass<Result/> at the end of </marks> tag.
<?xml version = "1.0"?>
<class>
<student rollno = "393">
<firstname>dinkar</firstname>
<lastname>kad</lastname>
<nickname>dinkar</nickname>
<marks>85</marks>
</student>
<student rollno = "493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>vinni</nickname>
<marks>95</marks>
</student>
<student rollno = "593">
<firstname>jasvir</firstname>
<lastname>singn</lastname>
<nickname>jazz</nickname>
<marks>90</marks>
</student>
</class>
在以下 ModifyXML.java 程序中,我们创建了SAXParser对象并解析了输入文件。我们用必需的回调方法实现了Handler类,并利用writeFile()方法将更新的内容写入文件。我们使用了一个字符串数组来存储内容并将其写入文件。
In the following ModifyXML.java program, we have created SAXParser object and parsed the input file. We have implemented the Handler class with the necessary call back methods and writeFile() method to write the updated content into the file. We have used an array of String to store and write the content to the file.
import java.io.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import org.xml.sax.helpers.DefaultHandler;
//Implementing a Handler class
class UserDemoHandler extends DefaultHandler {
static String displayText[] = new String[1000];
static int numberLines = 0;
static String indentation = "";
public void startDocument() {
displayText[numberLines] = indentation;
displayText[numberLines] += "<?xml version = \"1.0\" encoding = \""+
"UTF-8" + "\"?>";
numberLines++;
}
public void processingInstruction(String target, String data) {
displayText[numberLines] = indentation;
displayText[numberLines] += "<?";
displayText[numberLines] += target;
if (data != null && data.length() > 0) {
displayText[numberLines] += ' ';
displayText[numberLines] += data;
}
displayText[numberLines] += "?>";
numberLines++;
}
public void startElement(String uri, String localName, String qualifiedName,
Attributes attributes) {
displayText[numberLines] = indentation;
indentation += " ";
displayText[numberLines] += '<';
displayText[numberLines] += qualifiedName;
if (attributes != null) {
int numberAttributes = attributes.getLength();
for (int loopIndex = 0; loopIndex < numberAttributes; loopIndex++) {
displayText[numberLines] += ' ';
displayText[numberLines] += attributes.getQName(loopIndex);
displayText[numberLines] += "=\"";
displayText[numberLines] += attributes.getValue(loopIndex);
displayText[numberLines] += '"';
}
}
displayText[numberLines] += '>';
numberLines++;
}
public void characters(char characters[], int start, int length) {
String characterData = (new String(characters, start, length)).trim();
if(characterData.indexOf("\n") < 0 && characterData.length() > 0) {
displayText[numberLines] = indentation;
displayText[numberLines] += characterData;
numberLines++;
}
}
public void endElement(String uri, String localName, String qualifiedName) {
indentation = indentation.substring(0, indentation.length() - 4) ;
displayText[numberLines] = indentation;
displayText[numberLines] += "</";
displayText[numberLines] += qualifiedName;
displayText[numberLines] += '>';
numberLines++;
if (qualifiedName.equals("marks")) {
startElement("", "Result", "Result", null);
characters("Pass".toCharArray(), 0, "Pass".length());
endElement("", "Result", "Result");
}
}
public void writeFile(FileWriter filewriter) throws IOException {
for(int loopIndex = 0; loopIndex < numberLines; loopIndex++) {
filewriter.write(displayText[loopIndex].toCharArray());
filewriter.write('\n');
System.out.println(displayText[loopIndex].toString());
}
filewriter.close();
}
}
public class ModifyXML extends DefaultHandler {
public static void main(String args[]) {
try {
//Creating SAXParser object
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
//Reading the XML
File inputFile = new File("src/input.txt");
//Creating object for Handler class
UserDemoHandler userHandler = new UserDemoHandler();
//Parsing the XML
saxParser.parse(inputFile, userHandler);
//Writing the updated content into file
FileWriter filewriter = new FileWriter("src/newfile.xml");
userHandler.writeFile(filewriter);
}
catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
输出窗口显示在向每个学生元素中添加结果元素后更新的XML文档内容。
The output window displays the updated content of the XML document after adding result element to each student element.
<?xml version = "1.0" encoding = "UTF-8"?>
<class>
<student rollno = "393">
<firstname>
dinkar
</firstname>
<lastname>
kad
</lastname>
<nickname>
dinkar
</nickname>
<marks>
85
</marks>
<Result>
Pass
</Result>
</student>
<student rollno = "493">
<firstname>
Vaneet
</firstname>
<lastname>
Gupta
</lastname>
<nickname>
vinni
</nickname>
<marks>
95
</marks>
<Result>
Pass
</Result>
</student>
<student rollno = "593">
<firstname>
jasvir
</firstname>
<lastname>
singn
</lastname>
<nickname>
jazz
</nickname>
<marks>
90
</marks>
<Result>
Pass
</Result>
</student>
</class>