先提供一个简单的XML文件,谁能帮我解析
<speech>
<speaker>catesby</speaker>
<line>The princes both make high account of you;</line>
<stagedir>aside</stagedir>
<line>For they account his head upon the bridge.</line>
</speech>

解决方案 »

  1.   

    public class TestGetPart
    {
        public TestGetPart()
        {
        }
        public static void println( String  message )
        {
                System.out.println( message );
        }    private static org.w3c.dom.Document getParsedXmlDoc(java.io.InputStream XmlInput)
        {
            org.w3c.dom.Document indoc=null;
            javax.xml.parsers.DocumentBuilderFactory factory;
            javax.xml.parsers.DocumentBuilder builder;
            try
            {
                factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
                factory.setValidating( false );
                builder = factory.newDocumentBuilder();
                indoc = builder.parse( XmlInput );
                indoc.normalize();
            }
            catch(Exception e)
            {
                println("解析文件错,XML文件格式不对。堆栈信息如下");
            }
            return indoc;
        }
        public static int spaceStep,spaceCount;
        public static void printDomTree(org.w3c.dom.Node node)
        {
                spaceStep = 4;
                spaceCount = 0;
                try{
                    saveDoc( node );
                } catch (Exception e)
                {
                    println(e.toString() );
                }
        }
        private static String addSpace(String line,int totalSpace)
        {
            String sp = "";
            for(int i=0;i<(totalSpace-line.length())/2;i++)
                sp+="-";
            if (line.length()%2!=0)
            {
                line+="-";
            }
            return sp+line+sp;
        }
        protected static String getSpace()
        {
            String str="";
            for(int i=0;i<spaceCount;i++)
                str = str +" ";
            return str;
        }
        public static void print( String message )
        {
                System.out.print( message );
        }    private static void print( String str , boolean space ) throws java.io.IOException
        {
            if ( space )
                str = getSpace() + str;
            print( str );
        }    private static void println( String str ,boolean space ) throws java.io.IOException
        {
            if ( space )
                str = getSpace() + str;
            str+="\r\n";
            print( str );
        }    private static void saveDoc(org.w3c.dom.Node node) throws java.io.IOException
        {
            if ( node==null )
                print( "" ,false );
            else if (  node.getNodeName().indexOf("#")>=0 )
            {
                String name = node.getNodeName().trim(); String value = node.getNodeValue().trim();
                if (name.equals("#text")&&value.equals("")) return ;
                println(value,true );
    //            println( "[name]:\""+node.getNodeName().trim()+"\"[value]:\""+node.getNodeValue().trim()+"\"" ,true );
                return ;
            }
            else if ( node.getFirstChild() == null )
                {
                        print( "<" + node.getNodeName() ,true );
                        for(int i=0;i<(node.getAttributes()).getLength();i++)
                        {
                            org.w3c.dom.Node attrNode = node.getAttributes().item(i);
                            print(" "+ attrNode.getNodeName()+"=\""+attrNode.getNodeValue()+"\"",false );
                        }
                        println("/>",false);
                }
                 else
                 {
                    print( "<" + node.getNodeName() ,true );
                    for(int i=0;i<(node.getAttributes()).getLength();i++)
                    {
                        org.w3c.dom.Node attrNode = node.getAttributes().item(i);
                        print(" "+ attrNode.getNodeName()+"=\""+attrNode.getNodeValue()+"\"",false );
                    }
                    println(">",false);
                    spaceCount += spaceStep;
                    for(int i=0;i<node.getChildNodes().getLength();i++)
                    {
                        saveDoc( node.getChildNodes().item( i ) );
                    }
                    spaceCount -= spaceStep;
                    println( "</" + node.getNodeName() +">",true);
                 }
        }    public static void printTextAsXml(String text)
        {
                try
                {
                    java.io.ByteArrayInputStream sbi = new java.io.ByteArrayInputStream(text.getBytes());
                    org.w3c.dom.Document indoc = getParsedXmlDoc(sbi);
                    if (indoc != null)
                    {
                        printDomTree(indoc.getLastChild());
                    }
                }catch(Throwable t)
                {
                    println( t.toString() );
                    println("Error happened while parsing xml,Original text is:\r\n"+text);            }
        }
        public static void main(String[] args)
        {
            String text = "<root><r>asas</r><r>asas</r></root>";
            printTextAsXml(text);
        }
    }
      

  2.   

    上面的代码会把你的xml解析为带有空格缩进的格式,然后输出。
    这样便于浏览。
    中间的解析过程用的就是DOM,含有递归处理过程。如:把main方法内的string换成楼主的,
        public static void main(String[] args)
        {
            String text = "<speech>"
    +"<speaker>catesby</speaker>"
    +"<line>The princes both make high account of you;</line>"
    +"<stagedir>aside</stagedir>"
    +"<line>For they account his head upon the bridge.</line>"
    +"</speech>";
            printTextAsXml(text);
        }
    会输出:<speech>    <speaker>        catesby    </speaker>    <line>        The princes both make high account of you;    </line>    <stagedir>        aside    </stagedir>    <line>        For they account his head upon the bridge.    </line></speech>
      

  3.   

    用sax解析
    不过作这个有用吗
      

  4.   

    用 SAX的例子:
    public class TestParseXml
    {
        private static String tag;
        class MyHandler
            extends org.xml.sax.helpers.DefaultHandler
        {
            private String part = null;
            private String getAttr(org.xml.sax.Attributes t)
            {
                String s="";
                for(int i=0;i<t.getLength();i++)
                {
                    s=s+" " +t.getQName(i) +"=\""+ t.getValue(i)+"\"";
                }
                return s;
            }        public void startElement(String uri, String localName, String qName,
                                     org.xml.sax.Attributes attributes)
            {
                if (qName.equals(tag))
                {
                    part = "<" + tag + getAttr(attributes)+ ">";
    //                part="";
                }
                else if (part != null)
                {
                    part += "<" + qName + getAttr(attributes) + ">";
                }
            }
            public void endElement(String uri, String localName, String qName)
            {
                if (qName.equals(tag))
                {
                    part += "</" + tag + ">";
                    System.out.println(part);
                }
                else
                {
                    part += "</" + qName + ">";
                }
            }
            public void characters(char[] ch, int start, int length)
            {
                part += new String(ch, start, length);
            }
        }
        public static void setFilterTag(String tag)
        {
            TestParseXml.tag = tag;
        }    public static java.io.InputStream getXmlStream()
        {
            String xml = "<root><r/><r><k p=\"3\"/><xx test=\"hello!\">ddd</xx></r><c><p name=\"5\">erw</p></c><r>trter</r><aa><r>ff</r></aa></root>";
            setFilterTag("r");
            return new java.io.ByteArrayInputStream(xml.getBytes());
        }
        public static void main(String[] args) throws Exception
        {
            javax.xml.parsers.SAXParserFactory saxParserFtr =
                javax.xml.parsers.SAXParserFactory.newInstance();
            javax.xml.parsers.SAXParser parser = saxParserFtr.newSAXParser();
            java.io.InputStream is = getXmlStream();
            parser.parse(new org.xml.sax.InputSource(is),
                         new TestParseXml().new MyHandler());
        }
    }
      

  5.   

    下载xerces后察看Xerces-J-bin.2.0.2\xerces-2_0_2\samples
    在这里有很多的例子下载地址:dsef
      

  6.   

    来迟了
    有XML问题也可尽管发问to my web: vcvj.com
      

  7.   

    太落后了,用jdom几句话就搞定了,可以参考jdom资料
      

  8.   

    to: medusagjf(郭婉仪) 那非常好啊:)
    你用jdom把上面两个例子都实现一遍,代码贴出来,
    让我们也学习一下:)谢谢!