📄 xmlprocessor.java
字号:
package jwo.jpss.utilities; // Part of the JPSS utilities package.
import javax.xml.parsers.*; // For Document builder factory.
import org.xml.sax.*; // For SAX Exception handling.
import org.w3c.dom.*; // For document object model (DOM).
import java.io.*; // For file handling.
import java.util.*; // For Vector collection.
// *********************************************************************
/** Handles XML processing allowing the reading and writing of XML files.
* Uses the Document Object Model (DOM) to store the tree of nodes
* represented by the XML file.
* @author Jo Wood.
* @version V1.3 29th August, 2001.
*/
// *********************************************************************
public class XMLProcessor
{
// -------------------- Object Variables ---------------------
private int indent; // Indent level.
private Document dom; // Document object model.
private PrintWriter out; // Output stream.
private Vector matches; // List of text matches from search.
// ---------------------- Constructors -----------------------
/** Creates an XML processor using the given DOM.
* @param DOM to use in processor.
*/
public XMLProcessor(Document dom)
{
this.dom = dom;
}
/** Reads the given XML file and constructs a DOM from it.
* @param fileName Name of XML file to read.
*/
public XMLProcessor(String fileName)
{
readXML(fileName);
}
// ------------------------- Methods ---------------------------
/** Reads the given XML file and converts it into a DOM.
* @param fileName Name of XML file to convert.
* @return True if converted successfully.
*/
public boolean readXML(String fileName)
{
// Create a DocumentBuilder using the DocumentBuilderFactory.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
indent = 0;
try
{
db = dbf.newDocumentBuilder();
}
catch (ParserConfigurationException e)
{
System.out.println("Problem finding an XML parser:\n"+e);
return false;
}
// Try to parse the given file and store XML nodes in the DOM.
try
{
dom = db.parse(new File(fileName));
}
catch (SAXException e)
{
System.out.println("Problem parsing document: "+e.getMessage());
dom = db.newDocument();
return false;
}
catch (IOException e)
{
System.out.println("Problem reading "+fileName);
return false;
}
return true;
}
/** Displays the DOM stored within this class as an XML file
* on standard output.
*/
public boolean writeXML()
{
out = new PrintWriter(System.out);
indent = 0;
outputNodeAsXML(dom);
out.close();
return true;
}
/** Converts the DOM stored within this class into an XML file.
* @param fileName Name of file to contain the XML.
* @return true if successful XML generation.
*/
public boolean writeXML(String fileName)
{
if (dom == null)
{
System.out.println("Error: No document object model to process.");
return false;
}
// Open file for output.
try
{
out = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
}
catch (IOException e)
{
System.out.println("Error: Problem creating XML file: "+fileName);
return false;
}
// Start recursive output of the whole DOM.
indent = 0;
outputNodeAsXML(dom);
// Close output and leave.
out.close();
return true;
}
/** Searches for a given element and returns all text nodes
* associated with it.
* @param element Element to search for.
* @return Array of strings associated with all occurrences
* of the given element.
*/
public String[] search(String element)
{
// Search for text nodes associated with element.
matches = new Vector();
search(dom,element);
// Convert match vector into an array.
String[] matchArray = new String[matches.size()];
matches.toArray(matchArray);
return matchArray;
}
// ---------------------- Private Methods --------------------------
/** Converts the given DOM node into XML. Recursively converts
* any child nodes.
* @param node DOM Node to display.
*/
private void outputNodeAsXML(Node node)
{
// Store node name, type and value.
String name = node.getNodeName(),
value = makeFriendly(node.getNodeValue());
int type = node.getNodeType();
// Ignore empty nodes (e.g. blank lines etc.)
if ((node==null) || ((value != null) && (value.trim().equals(""))))
return;
switch (type)
{
case Node.DOCUMENT_NODE: // Start of document.
{
out.println("<?xml version=\"1.0\" ?>");
// Output the document's child nodes.
NodeList children = node.getChildNodes();
for (int i=0; i<children.getLength(); i++)
outputNodeAsXML(children.item(i));
break;
}
case Node.ELEMENT_NODE: // Document element with attributes.
{
// Output opening element tag.
indent++;
indent();
out.print("<"+name);
// Output any attributes the element might have.
NamedNodeMap attributes = node.getAttributes();
for (int i=0; i<attributes.getLength(); i++)
{
Node attribute = attributes.item(i);
out.print(" "+attribute.getNodeName()+
"=\""+attribute.getNodeValue()+"\"");
}
out.print(">");
// Output any child nodes that exist.
NodeList children = node.getChildNodes();
for (int i=0; i<children.getLength(); i++)
outputNodeAsXML(children.item(i));
break;
}
case Node.CDATA_SECTION_NODE: // Display text.
case Node.TEXT_NODE:
{
out.print(value);
break;
}
case Node.COMMENT_NODE: // Comment node.
{
indent++;
indent();
out.print("<!--"+value+"-->");
indent--;
break;
}
case Node.ENTITY_REFERENCE_NODE: // Entity reference nodes.
{
indent++;
indent();
out.print("&"+name+";");
indent--;
break;
}
case Node.PROCESSING_INSTRUCTION_NODE: // Processing instruction.
{
indent++;
indent();
out.print("<?"+name);
if ((value != null) && (value.length() > 0))
out.print(" "+value);
out.println("?>");
indent--;
break;
}
}
// Finally output closing tags for each element.
if (type == Node.ELEMENT_NODE)
{
out.print("</"+node.getNodeName()+">");
indent--;
indent();
}
}
/** Searches for a given element and updates list of matching text.
* @param node Node to start search from.
* @param element Element to search for.
*/
private void search(Node node, String element)
{
if (node.getNodeName().equalsIgnoreCase(element))
{
// Match found, so look for text in children.
NodeList children = node.getChildNodes();
for (int i=0; i<children.getLength(); i++)
{
Node child = children.item(i);
if ((child.getNodeType() == Node.CDATA_SECTION_NODE) ||
(child.getNodeType() == Node.TEXT_NODE))
matches.add(child.getNodeValue());
}
}
if ((node.getNodeType() == Node.DOCUMENT_NODE) ||
(node.getNodeType() == Node.ELEMENT_NODE))
{
// Search child nodes.
NodeList children = node.getChildNodes();
for (int i=0; i<children.getLength(); i++)
search(children.item(i),element);
}
}
/** Converts a given string into XML-friendly code by replacing
* quotes, triangular brackets etc. with their symbolic equivalent.
* @param text Text to process.
* @return Processed text with XML friendly symbols.
*/
private static String makeFriendly(String text)
{
StringBuffer newText = new StringBuffer();
if (text == null)
return null;
int numCharacters = text.length();
for (int i=0; i<numCharacters; i++)
{
char ch = text.charAt(i);
switch (ch)
{
case '<':
{
newText.append("<");
break;
}
case '>':
{
newText.append(">");
break;
}
case '&':
{
newText.append("&");
break;
}
case '"':
{
newText.append(""");
break;
}
default:
{
newText.append(ch);
}
}
}
return newText.toString();
}
/** Indents output to current tree depth.
*/
private void indent()
{
out.println();
for (int i=1; i<indent; i++)
out.print(" ");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -