还是说的详细点
我要做的是把JAVA的代码中结构转化为XML文件
现在JAVA代码中类名、方法名、变量都能获得了但是就是不知道怎么写XML本人对XML不甚了解
看了几天书,不知道其所云(因为不知道我需要的是哪些知识,给我感觉怎么都在讲XML如何显示,JAVA如何解析)希望个位高手不吝赐教
任何方式都好
谢谢

解决方案 »

  1.   

    这是删除接点的例子import java.awt.*;
    import java.awt.event.*;
    import org.apache.xerces.parsers.DOMParser;
    import org.xml.sax.SAXException;
    import  java.awt.*;  
    import  java.awt.event.*;  
    import  org.apache.xerces.parsers.DOMParser;  
    import  org.xml.sax.SAXException;  
    import  org.w3c.dom.Document;  
    import  org.w3c.dom.Node;  
    import  org.w3c.dom.NodeList;  
    import  java.io.IOException;  
    import  org.w3c.dom.NamedNodeMap;  
     
    import  java.io.*;  
    import  org.w3c.dom.*;  
    import  org.apache.xerces.dom.*;  
    import  org.apache.xml.serialize.*;  
    import  org.apache.xerces.parsers.DOMParser;  
    import  javax.xml.parsers.DocumentBuilder;  
    import  javax.xml.parsers.DocumentBuilderFactory;  
     
     
    class  TjNode  extends  Frame  {
      
        public  static  void  main(String  args[])  {                         
           DocumentBuilder  parser;  
           DocumentBuilderFactory  factory  =  DocumentBuilderFactory.newInstance();        
           
           try{
             
               parser  =  factory.newDocumentBuilder();  
               Document  doc  =  parser.parse("system_file.xml");              
               NodeList  newKey=doc.getElementsByTagName("Name");  
               for(int  i=0;i<newKey.getLength();i++){  
                Node  aNode=newKey.item(i);  
                String  newString=  aNode.getFirstChild().getNodeValue().toString();  
                System.out.println(newString);                     
                if(newString.equals("dfg")){   
                 aNode.getParentNode().removeChild(aNode);  
                }  
              }  
               File  _outputFile=new  File("system_file.xml");  
               OutputFormat  outputFormat=new  OutputFormat("XML","gb2312",true);  
               FileWriter  fileWriter=new  FileWriter(_outputFile);  
               XMLSerializer  xmlSerializer=new  XMLSerializer(fileWriter,outputFormat);  
               xmlSerializer.asDOMSerializer();  
               xmlSerializer.serialize(doc.getDocumentElement());  
           }catch  (Exception  evc){  
               System.out.println(evc.toString());  
           }  
        }  
    }这是更新的例子DocumentBuilder parser;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try{
          parser = factory.newDocumentBuilder();
          Document doc = parser.parse("system_file.xml");
          Element Name=doc.createElement("Name");
          Name.setAttribute("savepath",pathText.getText());
          Name.setAttribute("savesystem",system_String);
          Name.appendChild(doc.createTextNode(treenameText.getText()));
        
          doc.getDocumentElement().appendChild(Name);
          File _outputFile=new File("system_file.xml");
          OutputFormat outputFormat=new OutputFormat("XML","gb2312",true);
          FileWriter fileWriter=new FileWriter(_outputFile);
          XMLSerializer xmlSerializer=new XMLSerializer(
              fileWriter,outputFormat);
          xmlSerializer.asDOMSerializer();
          xmlSerializer.serialize(doc.getDocumentElement());
          getnewtreeNode=treenameText.getText();
        }catch (Exception evc){
          System.out.println(evc.toString());
        }写xml一样看看就可以了。这些包在jbuilder内都有。
    或者去http://jakarta.apache.org下载这个例子是把xml文件变成javabeanimport org.apache.xerces.parsers.SAXParser;
    import org.xml.sax.InputSource;
    import java.io.FileInputStream;
    import java.util.Hashtable;
    import java.util.Enumeration;
    import org.xml.sax.helpers.DefaultHandler;
    import org.xml.sax.Attributes;class Employee{

    private String id="";
    private Profile profile=null;

    public void setId(String newId){
    id=newId;
    }

    public String getId(){
    return id;
    }

    public void setProfile(Profile newProfile){
    profile=newProfile;
    }

    public String toString(){
    return "Employee: "+id+"\n"
    +profile.getFirstName()+"\n"
    +profile.getLastName();
    }
    }class Profile{

    String firstName="";
    String lastName="";

    public void setFirstName(String newFirstName){
    firstName=newFirstName;
    }

    public String getFirstName(){
    return firstName;
    }

    public void setLastName(String newLastName){
    lastName=newLastName;
    }
    public String getLastName(){
    return lastName;
    }
    }

    class EmployeeBuilder extends DefaultHandler{

    private Hashtable employeeList=null;
    private Employee employee=null;
    private Profile profile=null;

    public void startDocument(){

    employeeList=new Hashtable();
    }

    public void endElement(String nameSpaceURI,String name,
    String qName){

    if(name.equals("employee")){
    employeeList.put(employee.getId(),employee);
    }
    }

    public void startElement(String namespaceURI,String name,
    String qName,Attributes atts){

    if(name.equals("employee")){
    employee=new Employee();
    employee.setId(atts.getValue("id"));
    }

    if(name.equals("profile")){
    profile=new Profile();

    profile.setFirstName(atts.getValue("firstName"));
    profile.setLastName(atts.getValue("lastName"));
    employee.setProfile(profile);
    }
    }

    public Hashtable getEmployess(){
    return employeeList;
    }
    }class SAXEmployeeExample1{

    public static void main(String args[]){

    EmployeeBuilder eBuilder=new EmployeeBuilder();

    try{
    SAXParser saxParser=new SAXParser();
    saxParser.setContentHandler(eBuilder);
    saxParser.parse(new InputSource(
    new FileInputStream("employees.xml")));
    Hashtable employees=eBuilder.getEmployess();
    Enumeration emps=employees.elements();
    while(emps.hasMoreElements()){
    Employee employee=(Employee)emps.nextElement();
    System.out.println(employee);
    }
    }catch(Exception ex){
    System.out.println(ex);
    }
    }
    }

    xml文件<?xml version="1.0"?>
    <employees>
    <employee id="A124-567">
    <profile firstName="Joe" lastName="Coder"/>
    </employee>
    <employee id="A1234-789">
    <profile firstName="Danny" lastName="shi"/>
    </employee>
    </employees>
    由于不是很清楚你的想法,所有多写了点.
      

  2.   

    dom解析,用
    try{
          DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
          DocumentBuilder builder=factory.newDocumentBuilder();
          doc=builder.newDocument();
      
          //获得TopicID
          int  i  = TaminoWrapper.GetUniqueID(dbURL);
          TopicID=String.valueOf(i);
          ParentID=TopicID;      Element root=doc.createElement("TOPIC");
          Element Issue1=doc.createElement("Issue");      Element RootID1=doc.createElement("RootID");
          RootID1.appendChild(doc.createTextNode("100"));
          Issue1.appendChild(RootID1);
          Element ParentID1=doc.createElement("ParentID");
          ParentID1.appendChild(doc.createTextNode(ParentID));
          Issue1.appendChild(ParentID1);      Element TopicName1=doc.createElement("TopicName");
          TopicName1.appendChild(doc.createTextNode(TopicName));
          Issue1.appendChild(TopicName1);      Element AuthorName1=doc.createElement("AuthorName");
          AuthorName1.appendChild(doc.createTextNode(AuthorName));
          Issue1.appendChild(AuthorName1);
         
          Element TopicID1=doc.createElement("TopicID");
          TopicID1.appendChild(doc.createTextNode(TopicID));
          Issue1.appendChild(TopicID1);
          Element AuthorID1=doc.createElement("AuthorID");
          AuthorID1.appendChild(doc.createTextNode("50"));
          Issue1.appendChild(AuthorID1);      Element content1=doc.createElement("content");
          content1.appendChild(doc.createTextNode(content));
          Issue1.appendChild(content1);      Element upDateTime1=doc.createElement("upDateTime");
          upDateTime1.appendChild(doc.createTextNode(upDateTime));
          Issue1.appendChild(upDateTime1);
           Element ReplyTimes1=doc.createElement("ReplyTimes");
          ReplyTimes1.appendChild(doc.createTextNode("0"));
          Issue1.appendChild(ReplyTimes1);      Element Mark1=doc.createElement("Mark");
          Mark1.appendChild(doc.createTextNode(Mark));
          Issue1.appendChild(Mark1);      Element BBSname1=doc.createElement("BBSname");
          BBSname1.appendChild(doc.createTextNode(BBSname));
          Issue1.appendChild(BBSname1);
      
         Element ViewTimes1=doc.createElement("ViewTimes");
          ViewTimes1.appendChild(doc.createTextNode("0"));
          Issue1.appendChild(ViewTimes1);     
          Element SignName1=doc.createElement("SignName");
          String Value=getUser.getUser("SignName",AuthorName);
          SignName1.appendChild(doc.createTextNode(Value));
          Issue1.appendChild(SignName1);      Element Photo1=doc.createElement("Photo");
          Value=getUser.getUser("Photo",AuthorName);
          Photo1.appendChild(doc.createTextNode(Value));
          Issue1.appendChild(Photo1);
     
          Element NickName1=doc.createElement("NickName");
          Value=getUser.getUser("NickName",AuthorName);
          NickName1.appendChild(doc.createTextNode(Value));
          Issue1.appendChild(NickName1);      Element Rank1=doc.createElement("Rank");
          Value=getUser.getUser("Rank",AuthorName);
          Rank1.appendChild(doc.createTextNode(Value));
          Issue1.appendChild(Rank1);      Element BBSID1=doc.createElement("BBSID");
          BBSID1.appendChild(doc.createTextNode(BBSID));
          Issue1.appendChild(BBSID1);
     
          Element SortTime1=doc.createElement("SortTime");
          SortTime1.appendChild(doc.createTextNode(SortTime));
          Issue1.appendChild(SortTime1);      root.appendChild(Issue1);
          doc.appendChild(root);  
          try{
            TaminoWrapper.Process(dbURL,doc,"BBS_topic");
          }
          catch(Exception ee)
              {out.println("提交失败");return;
          }    }
      }
        catch(Exception ex)
            {out.println("用户名错误");
      
        }
    类似我这样的代码可以把xml树组在内存里
      

  3.   

    先谢谢各位但是我的运行环境是jdk1.3.1
    不知道可以运行吗
    还有那些个包从什么地方可以获得(jdk1.3.1里边有吗)??请多多指教
      

  4.   

    找本书看看。关于JAVA&XML的书不少。
    还有这里:http://www-900.ibm.com/developerWorks/cn/education/xml/xmljava/tutorial/xmljava-menu.html
      

  5.   

    用JDom操作文件就不用用io的write写tag标记,不过存盘还要自己干的
      

  6.   

    我尝试着写了一个
    还可以
    但是为什么我用setAttribute()函数加的属性
    它要按照字母大小排序呢|?
    如何能叫它不排
      

  7.   

    ****************************************************
    但是我的运行环境是jdk1.3.1
    不知道可以运行吗
    还有那些个包从什么地方可以获得(jdk1.3.1里边有吗)??
    ****************************************************是可以运行的就是添加相应的包就可以了。
    到这里可以下载 Xerces-J http://xml.apache.org/dist/xerces-j;这是xml的解析器,上面需要的包和一些文档,例子。×××××××××××××××××××
    我尝试着写了一个
    还可以
    但是为什么我用setAttribute()函数加的属性
    它要按照字母大小排序呢|?
    如何能叫它不排
    ×××××××××××××××××××××××××这个是什么意思我不是很清楚。。如果还有问题在发信息给我。
    http://xml.apache.org/xalan-j/downloads.html  xalan-j(在是xml的样式(xslt);还有JAXP;如果你安装了JBuilder7的,这些包在\JBuilder7\lib下;
      

  8.   

    两位前辈:
    写xml目前已经不是我的问题了,关于那个包,我同学给我提供了jbuild下的一个叫xer**的包
    用dom方法也把xml写出来了,但是现在我写的这个xml有个问题,就是我加属性的顺序和我在ie下显示的顺序不一致
    例子:
    ******
    Element root=doc.createElement("root");
    root.setAttribute("c","3");//先加入的是c
    root.setAttribute("a","1");//再是a
    root.setAttribute("d","4");//再是d
    root.setAttribute("b","2");//最后是b
    ****假设生成a.xml文件
    前辈们:我预期想得到的是这样的文件
    <root c='3',a='1',d='4',b='2'/>
    即按照我加入属性的先后顺序显示
    然而
    ie下显示却是这样
    <root a='1',b='2',c='3',d='4'/>
    这样的话不是我预期要的东东
    希望大家给个解决方案
      

  9.   

    用JDOM来操作XML:(要加入一个是JDOM包到 classpath中)
    package demo.testjdom;import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.JDOMException;
    import org.jdom.input.SAXBuilder;
    import org.jdom.output.XMLOutputter;import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintStream;
    import java.util.Iterator;
    import java.util.List;public class CDCatalog {    File file = null;
        Document document = null;    public static void main(String args[]) {
            if (args.length > 0) {
                String xmlFile = args[0];
                CDCatalog catalog = new CDCatalog(xmlFile);            String action = args[1];            try {
                    if (args.length == 5) {
                        String title = args[2];
                        String artist = args[3];
                        String label = args[4];
                        if (action.equals("add")) {
                            catalog.addCD(title, artist, 
                                label);
                        } else if (action.equals("delete")) {
                            catalog.deleteCD(title, 
                                artist, label);
                        }
                    }                // save the changed catalog
                    catalog.save();
                } catch (Exception e) {
                    e.printStackTrace(System.err);
                }
            }
        }    public CDCatalog(String fileName) {
            try {
                file = new File(fileName);
                if (file.exists()) {
                    loadDocument(file);
                } else {
                    createDocument();
                }
            } catch (Exception e) {
                e.printStackTrace(System.err);
            }
        }    private void loadDocument(File file) 
        throws JDOMException {
            SAXBuilder builder = new SAXBuilder();
            document = builder.build(file);
        }    private void createDocument() {
            Element root = new Element("CDCatalog");
            document = new Document(root);
        }    public void addCD(String title, String artist, 
            String label) {
            Element cd = new Element("CD");
            cd.setAttribute("title",title);
            cd.setAttribute("artist",artist);
            cd.setAttribute("label",label);        document.getRootElement().getChildren().add(cd);
        }    public void deleteCD(String title, String artist,  
            String label) {
            List cds = document.getRootElement().getChildren();
            for (int i = 0; i < cds.size(); i++) {
                Element next = (Element)cds.get(i);
                if (next.getAttribute("title").getValue()
                    .equals(title) &&
                    next.getAttribute("artist").getValue()
                    .equals(artist) &&
                    next.getAttribute("label").getValue()
                    .equals(label)) {
                    next.detach();
                }
            }
        }    public void Save() throws IOException {
            XMLOutputter outputter = new XMLOutputter();
            FileWriter writer = new FileWriter(file);
            outputter.output(document,writer);
            writer.close();
        }
    }