How to convert String to DOM Document object in java?

前端 未结 4 1770
抹茶落季
抹茶落季 2020-12-15 18:28

I have a case like getting an XML and convert the XML elements to document object and getting the element values and attributes which i have been created already

Her

相关标签:
4条回答
  • 2020-12-15 18:48

    Either escape the double quotes with \

    String xmlString = "<element attribname=\"value\" attribname1=\"value1\"> pcdata</element>"
    

    or use single quotes instead

    String xmlString = "<element attribname='value' attribname1='value1'> pcdata</element>"
    
    0 讨论(0)
  • 2020-12-15 19:01
         public static void main(String[] args) {
        final String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"+
                                "<Emp id=\"1\"><name>Pankaj</name><age>25</age>\n"+
                                "<role>Developer</role><gen>Male</gen></Emp>";
       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
            DocumentBuilder builder;  
            try 
            {  
                builder = factory.newDocumentBuilder();  
                Document doc = builder.parse( new InputSource( new StringReader( xmlStr )) ); 
    
            } catch (Exception e) {  
                e.printStackTrace();  
            } 
      }
    
    0 讨论(0)
  • 2020-12-15 19:04

    you can try

    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader("<root><node1></node1></root>"));
    
    Document doc = db.parse(is);
    

    refer this http://www.java2s.com/Code/Java/XML/ParseanXMLstringUsingDOMandaStringReader.htm

    0 讨论(0)
  • 2020-12-15 19:09
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = db.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); //remove the parameter UTF-8 if you don't want to specify the Encoding type.
    

    this works well for me even though the XML structure is complex.

    And please make sure your xmlString is valid for XML, notice the escape character should be added "\" at the front.

    The main problem might not come from the attributes.

    0 讨论(0)
提交回复
热议问题