DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db =  factory.newDocumentBuilder();
Document doc = db.parse(new InputSource(new ByteArrayInputStream(xmlString.getBytes("gb2312"))));

解决方案 »

  1.   

    我要把下面的xml文档转换存到为Hashtable中,总出错,大家给指导一下!    Hashtable ht=new Hashtable();
        String xmlString="<xml><group><producelotid>1-1-1</producelotid><weight>20</weight></group>  <group><producelotid>1-1-2</producelotid><weight>30</weight></group></xml>";    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder db =  factory.newDocumentBuilder();
        Document doc = db.parse(new InputSource(new ByteArrayInputStream(xmlString.getBytes("gb2312"))));
        NodeList nodeList=doc.getChildNodes();
        for(int i=0;i<nodeList.getLength();i++){
          Node node=nodeList.item(i);
          String producelotid=node.getFirstChild().getFirstChild().getNodeValue();
          String weight=node.getLastChild().getNodeValue();
          ht.put(producelotid,weight);    }
        System.out.println("begin:");
        System.out.println(ht);
      

  2.   

    给你一段简单的代码,可以将String to Document
    public static Document string2Dom(String xml)throws ParserConfigurationException, IOException, SAXException {
    if (db == null) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    db = dbf.newDocumentBuilder();
    }
    return db.parse(new InputSource(new StringReader(xml)));
    }
      

  3.   

    谁能帮我调试一下这段程序,主要是想把xml文档里的数据存入一个Hashtable里:
        Hashtable ht=new Hashtable();
        String xmlString="<xml><group><producelotid>1-1-1</producelotid><weight>20</weight></group>  <group><producelotid>1-1-2</producelotid><weight>30</weight></group></xml>";    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder db =  factory.newDocumentBuilder();
        Document doc = db.parse(new InputSource(new ByteArrayInputStream(xmlString.getBytes("gb2312"))));
        System.out.println(doc);//这里输出为:[#document: null]
        NodeList nodeList=doc.getChildNodes();
        for(int i=0;i<nodeList.getLength();i++){
          Node node=nodeList.item(i);
          String producelotid=node.getFirstChild().getFirstChild().getNodeValue();
          String weight=node.getLastChild().getNodeValue();
          ht.put(producelotid,weight);    }
        System.out.println("begin:");
        System.out.println(ht);
      

  4.   

    doc = db.parse(inFile);
    这一句是解析的文件,我的程序中
    Document doc = db.parse(new InputSource(new ByteArrayInputStream(xmlString.getBytes("gb2312"))));
    解析字符串好像就不能得到正确的document对象?
      

  5.   

    你把String构造一个StringReader试试。
      

  6.   

    to zyymmm(为成为VC高手而奋斗) :你的程序((XmlDocument) doc).write(outWriter, "GB2312");造型错误,java.lang.ClassCastExceptionXmlDocument能格式化输出XML吗?