import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import org.w3c.dom.*;
//import com.ibm.xml.internal.MIME2Java;
//import com.ibm.xml.parsers.NonValidatingDOMParser;
import org.apache.xerces.parsers.DOMParser;/*
 * This class For COS Screens XML process only, include create common head xml, 
 * output document to harddist for MQ sending, Element processing
 * Creation date :  19/11/2002
 * @version :  1.0
 * @author  :  Happyegg
 */public class COSXMLProcessor { private static boolean canonical=false;
private static  String PRINTWRITER_ENCODING = "UTF8";
/**
 * Initializes a newly COSXMLProcessor_old object.<p>
 * Creation date :  19/11/2002
 */
public COSXMLProcessor() {
} /**
 * Obtain a new instance of a DOM Document object.<p>
 * Creation date :  19/11/2002
 * @return new Document object
 */
public Document createDoc() {
Document xmlDoc = null;
return xmlDoc;
}
/**
 * Obtain a new instance of a DOM Document object with given file.<p>
 * Creation date :  19/11/2002
 * amend date/reason  :  30/11/2002  ---  discards JAXP standard, use IBM instead to create Document
 * @param path source xml file path
 * @return new Document Object with given source
 */
public Document createDoc(String path) {
Document xmlDoc = null;
try{
java.io.File xmlP = new java.io.File(path);
if(xmlP.isFile()) {
DOMParser parser = new DOMParser();
parser.parse(path);
xmlDoc = parser.getDocument();
}
else {
byte[] bbb = path.getBytes("UTF-8");
java.io.ByteArrayInputStream iii = new java.io.ByteArrayInputStream(bbb);

org.xml.sax.InputSource asd = new org.xml.sax.InputSource(iii);

DOMParser parser = new DOMParser();
parser.parse(asd);
xmlDoc = parser.getDocument();
}
}
catch(Exception e){
System.out.println("[COSXMLProcessor].createDoc Error: " + e.toString());
}
return xmlDoc;
}
/**
 * Get the Element with given path.<p>
 * Creation date :  21/11/2002.
 * @param parentNode The node from which search begin.
 * @param selectPath search path, sample as : "ROOT/Class/Student".  Warning: selectPath is Case sensitive
 * @return The result Element or null if can not find.
 */
public Element selectSingleNode(Node parentNode,String selectPath) {
Element ele = (Element) parentNode;
Element selectEle = selectSingleNode(ele,selectPath);
return selectEle;
}
/**
 * Get the Element with given path.<p>
 * Creation date :  21/11/2002
 * @param parentEle The Element from which search begin
 * @param selectPath search path, sample as : "ROOT/Class/Student".  Warning: selectPath is Case sensitive
 * @return The result Element or null if can not find.
 */
public Element selectSingleNode(Element parentEle,String selectPath) {
Element selectEle = null;
int sepIndex = selectPath.indexOf("/");
String curString;
String nxtString;
if (sepIndex!=-1) {
curString = selectPath.substring(0,sepIndex);
nxtString = selectPath.substring(sepIndex+1);
}
else {
curString = selectPath;
nxtString = "";
}
NodeList nodeList = parentEle.getElementsByTagName(curString);
selectEle = (Element)nodeList.item(0); if ( (sepIndex!=-1) && (selectEle!=null) ) {
selectEle = selectSingleNode(selectEle,nxtString);
}
return selectEle;
}
/**
 * Get the NodeLIst with given path.<p>
 * Creation date :  21/11/2002
 * @param parentEle The Element from which search begin
 * @param selectPath search path, sample as : "ROOT/Class/Student".  Warning: selectPath is Case sensitive
 * @return The result Element or null if can not find.
 */
public NodeList selectNodes(Element parentEle,String selectPath) {
NodeList nodeList = null;
Element selectEle = null;
int sepIndex = selectPath.indexOf("/");
int nodeIndex = selectPath.lastIndexOf("/");
String nodeListString = "";
String searchString = ""; if (sepIndex==-1) {
nodeList = parentEle.getElementsByTagName(selectPath);
}
else {
searchString = selectPath.substring(0,nodeIndex);
nodeListString = selectPath.substring(nodeIndex+1);
selectEle = selectSingleNode(parentEle, searchString);
if (selectEle != null)
nodeList = selectEle.getElementsByTagName(nodeListString);
}
return nodeList;
}

/**
 * Get the value of all type of element.
 * Creation date :  21/11/2002.
 * @param inNode The Element which get value from.
 * @return Node value if it is Text Node or null if not.
 */
public String getNodeValue(Node inNode) {
//Because Element do not possess nodeValue, it must get it's childNode "#text" to set and 
//get value, 
String nodeValue = null;
Node txtNode = inNode.getFirstChild();
if (txtNode!=null) {
if (txtNode.getNodeType()==Node.TEXT_NODE) {
nodeValue = txtNode.getNodeValue();
}
}
return nodeValue;
}

/**
 * Get the value of all type of element.
 * Creation date :  21/11/2002.
 * @param inNode The Element which need to be set value.
 * @param nodeValue input nodeValue.
 */
public void setNodeValue(Node inNode,String nodeValue) {
//Because Element do not possess nodeValue, it must get it's childNode "#text" to set and 
//get value, so add nodeValue is not a easy job, it must be add as this method.
if (inNode.getNodeType()==Node.ELEMENT_NODE) {
Node textNode;
textNode = inNode.getFirstChild();
if ( (textNode==null) || (textNode.getNodeType()!=Node.TEXT_NODE) ) {
textNode = inNode.getOwnerDocument().createTextNode(nodeValue);
inNode.insertBefore(textNode,inNode.getFirstChild());
}
textNode.setNodeValue(nodeValue);
}
}

解决方案 »

  1.   

    /**
     * Create and return new Node with given path.  It does not create the Node witch has existed in the given path,
     * if you wanted to create a new Node with same same as existing Node, use jaxp method. <p>
     * Creation date :  28/11/2002
     * @param parentElement The Element from which begin
     * @param newElementPath create path, sample as : "ROOT/Class/Student".  Warning: newElementPath is Case sensitive
     * @return If newElementPath with invalid character, return null. Otherwise, return the new Element if create 
     * successfully or the Element whch has existed.
     */
    public Element createNode(Element parentElement,String newElementPath) {
    Element nextEle = null;
    Element newEle = null;
    try {
    int sepIndex = newElementPath.indexOf("/");
    String curString;
    String nxtString;
    if (sepIndex!=-1) {
    curString = newElementPath.substring(0,sepIndex);
    nxtString = newElementPath.substring(sepIndex+1);
    }
    else {
    curString = newElementPath;
    nxtString = "";
    }
    NodeList nodeList = parentElement.getElementsByTagName(curString);
    nextEle = (Element)nodeList.item(0);
    newEle = nextEle;
    if (nextEle==null) {
    nextEle = parentElement.getOwnerDocument().createElement(curString);
    parentElement.appendChild(nextEle);
    newEle = nextEle;
    }
    if ( sepIndex!=-1) {
    newEle = createNode(nextEle,nxtString);
    }
    }
    catch(Exception ePath) {
    //The error mainly cause by wrong newElementPath
    System.out.println( "[COSXMLProcessor].createNode Error: " + ePath.toString());
    newEle = null;
    }
    return newEle;
    } public static String getWriterEncoding( ) {
    return (PRINTWRITER_ENCODING);
    }// getWriterEncoding
    protected static Attr[] sortAttributes(NamedNodeMap attrs) {
    int len = (attrs != null) ? attrs.getLength() : 0;
    Attr array[] = new Attr[len];
    for ( int i = 0; i < len; i++ ) {
    array[i] = (Attr)attrs.item(i);
    }
    for ( int i = 0; i < len - 1; i++ ) {
    String name  = array[i].getNodeName();
    int    index = i;
    for ( int j = i + 1; j < len; j++ ) {
    String curName = array[j].getNodeName();
    if ( curName.compareTo(name) < 0 ) {
    name  = curName;
    index = j;
    }
    }
    if ( index != i ) {
    Attr temp    = array[i];
    array[i]     = array[index];
    array[index] = temp;
    }
    }
    return (array);
    } // sortAttributes(NamedNodeMap):Attr[]
    protected static String normalize(String s) {
    StringBuffer str = new StringBuffer();
    try{
    int len = (s != null) ? s.length() : 0;
    for ( int i = 0; i < len; i++ ) {
    char ch = s.charAt(i);
    switch ( ch ) {
    case '<': {
    str.append("&lt;");
    break;
    }
    case '>': {
    str.append("&gt;");
    break;
    }
    case '&': {
    str.append("&amp;");
    break;
    }
    case '"': {
    str.append("&quot;");
    break;
    }
    case '\r':
    case '\n': {
    if ( canonical ) {
    str.append("&#");
    str.append(Integer.toString(ch));
    str.append(';');
    break;
    }
    // else, default append char
    }
    default: {
    str.append(ch);
    }
    }
    }
    }catch(Exception e){
    System.out.println("[COSXMLProcessor].normalize Error: " + e.toString());
    return null;
    }
    return (str.toString());
    } // normalize(String):String
    public static void main(String[] args) { try{
    COSXMLProcessor xmlProcessor = new COSXMLProcessor();
    //String xmlPath = COSScreenMapping.genXMLPath(COSScreenMapping.XML_COMMON);
    String xmlPath = "";
    xmlPath = "<IMCPI01C xmlns:ais=\"http://www.hsbc.com/ais\" xmlns:svm=\"http://www.hsbc.com/svm\" xmlns:imc=\"http://www.hsbc.com/imc\" xmlns=\"http://www.hsbc.com/cos\"><conCtry>HK</conCtry><conInst>HBAP</conInst><conStkId>CO 12345</conStkId><conIssuanceBr>213</conIssuanceBr><conProdTyp>CO</conProdTyp><conProdCcy>HKD</conProdCcy><conStkTyp>A</conStkTyp><conStkVerNo>1</conStkVerNo><conDraweeBank></conDraweeBank><conDraweeBr></conDraweeBr><conCustCtry>HK</conCustCtry><conCustInst>HBAP</conCustInst><conCustId>CUSTID</conCustId><conAcctCtry></conAcctCtry><conAcctInst></conAcctInst><conAcctNo></conAcctNo><conAcctTyp></conAcctTyp><conChqTyp>11</conChqTyp><conMicrLineBr>23432</conMicrLineBr><userAction>CHANGE</userAction><lastUpdTm>2003-07-16 15:54:39.741774</lastUpdTm></IMCPI01C>"; xmlPath = "<IMCPI09C xmlns:ais=\"http://www.hsbc.com/ais\" xmlns:svm=\"http://www.hsbc.com/svm\" xmlns:imc=\"http://www.hsbc.com/imc\" xmlns=\"http://www.hsbc.com/cos\"><conCustCtry>HK</conCustCtry><conCustInst>HBAP</conCustInst><conCustId>CUSTID</conCustId><conCurrTblTmplFile diff=\"MOD\">Date.txt</conCurrTblTmplFile><conTmplDes>fsdafdsafdsafdsaf</conTmplDes><conFontTypVal>Courier</conFontTypVal><conFontSizeVal>11</conFontSizeVal><conWrapArdCol>1</conWrapArdCol><conColHdVal></conColHdVal><conColHdVal>Heading22</conColHdVal><conColHdVal>fadsfasdfas</conColHdVal><conColHdVal></conColHdVal><conColHdVal></conColHdVal><conColHdVal></conColHdVal><conColHdVal></conColHdVal><conColHdVal></conColHdVal><conColHdVal></conColHdVal><conColHdVal></conColHdVal><conColHdVal></conColHdVal><conColHdVal></conColHdVal><conColWdtVal>12</conColWdtVal><conColWdtVal>22</conColWdtVal><conColWdtVal>33</conColWdtVal><conColWdtVal></conColWdtVal><conColWdtVal></conColWdtVal><conColWdtVal></conColWdtVal><conColWdtVal></conColWdtVal><conColWdtVal></conColWdtVal><conColWdtVal></conColWdtVal><conColWdtVal></conColWdtVal><conColWdtVal></conColWdtVal><conColWdtVal></conColWdtVal><conColJstfVal>R</conColJstfVal><conColJstfVal>C</conColJstfVal><conColJstfVal>L</conColJstfVal><conColJstfVal></conColJstfVal><conColJstfVal></conColJstfVal><conColJstfVal></conColJstfVal><conColJstfVal></conColJstfVal><conColJstfVal></conColJstfVal><conColJstfVal></conColJstfVal><conColJstfVal></conColJstfVal><conColJstfVal></conColJstfVal><conColJstfVal></conColJstfVal><conColDtTypVal>Amount with 2 decimals</conColDtTypVal><conColDtTypVal>Amount with no decimals</conColDtTypVal><conColDtTypVal>Amount with 2 decimals</conColDtTypVal><conColDtTypVal></conColDtTypVal><conColDtTypVal></conColDtTypVal><conColDtTypVal></conColDtTypVal><conColDtTypVal></conColDtTypVal><conColDtTypVal></conColDtTypVal><conColDtTypVal></conColDtTypVal><conColDtTypVal></conColDtTypVal><conColDtTypVal></conColDtTypVal><conColDtTypVal></conColDtTypVal><conTmplId>5555555555555555</conTmplId><conFileNam diff=\"MOD\">Date.txt</conFileNam><conFileTyp diff=\"NEW\">*</conFileTyp><conSrvIp diff=\"NEW\">133.4.0.103</conSrvIp><conSrvNam diff=\"NEW\">WSBCC</conSrvNam><conUpldDir diff=\"NEW\">COS/upload/PaymentDetails_TableTemplate/HKHBAPCUSTID/5555555555555555/</conUpldDir><userAction>CHANGE</userAction><lastUpdTm>2003-06-27 10:04:11.820943</lastUpdTm></IMCPI09C>";
    Document doc = xmlProcessor.createDoc(xmlPath); Element eleRoot = doc.getDocumentElement(); NodeList list = eleRoot.getChildNodes(); for(int i=0;i<list.getLength();i++){
    Node node = list.item(i);

    if(node.hasChildNodes() && node.getFirstChild().hasChildNodes()){
    System.out.println(node.getNodeName() + ":");
    NodeList childList = node.getChildNodes();
    System.out.print("     ");
    for(int j=0;j<childList.getLength();j++){
    Node childNode = childList.item(i);
    System.out.println(childNode.getNodeName() + ":" + xmlProcessor.getNodeValue(childNode));
    }
    }else{
    String content = xmlProcessor.getNodeValue(node);
    if(content==null) content ="";
    Node diff = node.getAttributes().getNamedItem("diff");

    if(diff!=null && !diff.toString().trim().equals("")) content= "*" + content;

    System.out.println(node.getNodeName() + ":" + content + "   " + node.getAttributes().getNamedItem("diff"));
    }
    }


    }catch(Exception e){
    System.out.println("Exception occurs:" +e);
    }
    //System.out.println(eleRoot);
    }
    }
      

  2.   

    用dom4j很好的
    看看Document这个类,由这个类看一些相关的类和操作!
      

  3.   

    下面是JAXP的例子。你可以自己改成一个通用的函数。    public static void main(String[] args) throws Exception {
            String fileName = "test.xml";
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(fileName);
            Element e0 = doc.getDocumentElement();
            NodeList nodes = e0.getChildNodes();
            for (int i = 0; i < nodes.getLength(); i++) {
                Node node = (Node) nodes.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element e = (Element) node;
                    if (e.getTagName().equals("test")) {
                        e.setTextContent("11111");// JDK 5.0 method
                    }
                }
            }
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer t = tf.newTransformer();
            t.transform(new DOMSource(doc), new StreamResult(new FileWriter(
                    fileName)));
        }}
      

  4.   

    I 'am so sorry!
    我没有说明白,我是希望替换掉标签及其内容,
    如:<test>Modify<test/>
    替换为<gender>male or female</gender>
    或直接将 <test>Modify<test/> 删除掉
      

  5.   

    忘了,我的开发环境是Linux ,JDK1.4
      

  6.   

    public class Test {    public static void main(String[] args) throws Exception {
            String fileName = "test.xml";
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(fileName);
            Element e0 = doc.getDocumentElement();
            NodeList nodes = e0.getChildNodes();
            for (int i = 0; i < nodes.getLength(); i++) {
                Node node = (Node) nodes.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element e = (Element) node;
                    if (e.getTagName().equals("test")) {
                        Element e1 = doc.createElement("gender");
                        // e1.setTextContent("male or female"); // JDK 5.0
                        setTextContent(e1, "male or female");
                        e0.replaceChild(e1, node);
                    }
                }
            }
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer t = tf.newTransformer();
            t.transform(new DOMSource(doc), new StreamResult(fileName));
        }    static void setTextContent(Element e, String str) {
            NodeList nl = e.getChildNodes();
            for (int i = 0; i < nl.getLength(); i++) {
                Node n = nl.item(i);
                if (n.getNodeType() == Node.TEXT_NODE) {
                    ((Text) n).setNodeValue(str);
                    break;
                }
            }
        }
    }
      

  7.   

    建议你认真看一下jdom就会有所收获