我也初学xml,今后多多指点!

解决方案 »

  1.   

    今天刚好无聊的很,于是就写了一个简单的例子。
    txml.xml文件,注意这里的方法,不然jdk自己带的那些解析器会
    解析出来一些乱七八糟的东西。
    <?xml version="1.0" standalone="yes"?>
    <GREETING id="test">ZosaTapo<person>Reic Yang</person></GREETING>java程序:
    import java.io.*;
    import java.lang.*;
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import org.w3c.dom.*;
    class txml
    {
    private static final String FILE_PATH="txml.xml";
    private Document doc=null;
    private DocumentBuilder docb=null;
    private DocumentBuilderFactory docbf=null;
    private Element root=null;
    public void loadDocument()
    {
    try
    {
    docbf=DocumentBuilderFactory.newInstance();
    docb=docbf.newDocumentBuilder();
    doc=docb.parse(new File(FILE_PATH));
    root=doc.getDocumentElement();
    }
    catch(ParserConfigurationException e){e.printStackTrace();}
    catch(SAXException e){e.printStackTrace();}
    catch(IOException e){e.printStackTrace();}
    }

    public Element getRoot()
    {
    return root;
    }
    public Document getDoc()
    {
    return doc;
    }
    public static void spaces(int depth)
    {
    //print prefix space to show level
    for(int d=0;d<depth;d++)
    {
    System.out.print("  ");
    }
    //System.out.println();
    }

    public static void printTree(Node root,int depth)
    {
    System.out.println();
    //print attributes
    if(root.hasAttributes())
    {
    System.out.println("******Node Attributes List******");
    NamedNodeMap namednodemap=root.getAttributes();
    for(int a=0;a<namednodemap.getLength();a++)
    {
    spaces(depth);
    System.out.println(namednodemap.item(a).getNodeName()
    +" : "+namednodemap.item(a).getNodeValue());
    }
    }

    //print nodes
    NodeList nodelist=root.getChildNodes();
    spaces(depth);
    System.out.println("******Node ChildNodes List******");
    spaces(depth);
    System.out.println("Nodes Total:"+nodelist.getLength());
    for(int n=0;n<nodelist.getLength();n++)
    {
    Node node=nodelist.item(n);

    spaces(depth);
    System.out.print("Node Type :"+node.getNodeType());
    System.out.print("  Node Name :"+node.getNodeName());
    System.out.print("   Node Value :"+node.getNodeValue());
    System.out.println();

    if(node.getNodeType()==1)
    {
    printTree(node,depth+1);
    }
    }
    System.out.println();
    }
    public static void main(String args[])
    {
    txml t=new txml();
    t.loadDocument();
    Document doc=t.getDoc();
    Element root=t.getRoot();
    System.out.println("+++++++++++++++++++++++++++++++++");
    System.out.println("+          Node List            +");
    System.out.println("+++++++++++++++++++++++++++++++++");
    printTree(root,0);
    }
    }
      

  2.   

    多谢楼上大虾指点,一定好好演示该例!另外,我只有Jaxp包,是否需要其它的包...谢谢!!!!