How to create a XML object from String in Java?

后端 未结 2 1956
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 20:15

I am trying to write a code that helps me to create a XML object. For example, I will give a string as input to a function and it will return me a XMLObject.



        
相关标签:
2条回答
  • 2020-12-02 20:25

    If you can create a string xml you can easily transform it to the xml document object e.g. -

    String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><a><b></b><c></c></a>";  
    
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
    DocumentBuilder builder;  
    try {  
        builder = factory.newDocumentBuilder();  
        Document document = builder.parse(new InputSource(new StringReader(xmlString)));  
    } catch (Exception e) {  
        e.printStackTrace();  
    } 
    

    You can use the document object and xml parsing libraries or xpath to get back the ip address.

    0 讨论(0)
  • 2020-12-02 20:46

    try something like

    public static Document loadXML(String xml) throws Exception
    {
       DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
       DocumentBuilder bldr = fctr.newDocumentBuilder();
       InputSource insrc = new InputSource(new StringReader(xml));
       return bldr.parse(insrc);
    }
    
    0 讨论(0)
提交回复
热议问题