http://www.csdn.net/develop/Read_Article.asp?Id=19171

解决方案 »

  1.   

    http://www.csdn.net/develop/Read_Article.asp?Id=19171
      

  2.   


    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 = "<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);
        }
    }
      

  3.   

    JDOM在更新xml方面比较方便,
    其他的,与JDK1.4方面相比,优势不是很明显。
      

  4.   

    利用DOM读取XML文件的程序:
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import java.io.*;/**
     *使用DOM提取XML内容的例子
     */
    class BookParser{
    public static void main(String[] args){
    try{
    //获取一个XML解析器
    DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
    DocumentBuilder builder=factory.newDocumentBuilder();
    //解析XML文件
    Document document=builder.parse(new File("books.xml"));
    //去掉XML文档中空白部分
    document.normalize();
    //获取根节点并打印根节点的名称
    Element root=document.getDocumentElement();
    System.out.println("根原始的名称:"+root.getTagName());
    //获取所有的"book"标记,它是一个NodeList对象
    NodeList books=root.getElementsByTagName("book");
    //遍历NodeList
    System.out.println("书本列表");
    for(int i=0;i<books.getLength();i++){
    //获取books中的每一个元素
    Element book=(Element)books.item(i);
    //获取每个"book"标记的"id"属性
    String book_id=book.getAttribute("id");//或book.getAttributeNode("id").getValue();
    System.out.println("序号:"+book_id);
    //获取"book"标记下的每个元素
    System.out.print("作者:");
    System.out.println(book.getElementsByTagName("author").item(0).getFirstChild().getNodeValue());
    System.out.print("标题:");
    System.out.println(book.getElementsByTagName("title").item(0).getFirstChild().getNodeValue());
    //获取"publish_date"元素
    Element publishDate=(Element)book.getElementsByTagName("publish_date").item(0);
    //获取"publish_date"元素下的每个子元素
    String year=publishDate.getElementsByTagName("year").item(0).getFirstChild().getNodeValue();
    String month=publishDate.getElementsByTagName("month").item(0).getFirstChild().getNodeValue();
    String day=publishDate.getElementsByTagName("day").item(0).getFirstChild().getNodeValue();
    System.out.println("出版日期:"+year+"年"+month+"月"+day+"日");
    System.out.print("描述:");
    System.out.println(book.getElementsByTagName("description").item(0).getFirstChild().getNodeValue());
    System.out.println("--------------------");
    }
    }
    catch(Exception e2){}
    }
    }相应的XML文件:
    <?xml version="1.0" encoding="UTF-8"?>
    <catalog>
    <book id="bk101">
    <author>Gambardella, Matthew</author>
    <title>XML Developer's Guide</title>
    <publish_date>
      <year>2000</year>
      <month>10</month>
      <day>1</day>
    </publish_date>
    <description>An in-depth look at creating applications with XML.</description>
    </book>
    <book id="bk102">
    <author>Ralls, Kim</author>
    <title>Midnight Rain</title>
    <publish_date>
      <year>2000</year>
      <month>12</month>
      <day>16</day>
    </publish_date>
    <description>A former architect battles corporate zombies.</description>
    </book>
    <book id="bk103">
    <author>Corets, Eva</author>
    <title>Maeve Ascendant</title>
    <publish_date>
      <year>2000</year>
      <month>11</month>
      <day>17</day>
    </publish_date>
    <description>After the collapse of a nanotechnology society in England.</description>
    </book>
    <book id="bk104">
    <author>leony</author>
    <title>Maeve Ascendant</title>
    <publish_date>
      <year>2000</year>
      <month>11</month>
      <day>17</day>
    </publish_date>
    <description>XML</description>
    </book>
    </catalog>
    把两个文件copy在同一目录下,编译运行即可