【问题标题】:How to parse a String containing XML in Java and retrieve the value of the root node?如何在 Java 中解析包含 XML 的字符串并检索根节点的值?
【发布时间】:2012-01-14 13:29:38
【问题描述】:

我有一个包含

的字符串形式的 XML
<message>HELLO!</message> 

我怎样才能得到字符串“你好!”来自 XML?这应该很容易,但我迷路了。 XML 不在文档中,它只是一个字符串。

【问题讨论】:

    标签: java xml root


    【解决方案1】:

    使用 JDOM

    String xml = "<message>HELLO!</message>";
    org.jdom.input.SAXBuilder saxBuilder = new SAXBuilder();
    try {
        org.jdom.Document doc = saxBuilder.build(new StringReader(xml));
        String message = doc.getRootElement().getText();
        System.out.println(message);
    } catch (JDOMException e) {
        // handle JDOMException
    } catch (IOException e) {
        // handle IOException
    }
    

    使用 Xerces DOMParser:

    String xml = "<message>HELLO!</message>";
    DOMParser parser = new DOMParser();
    try {
        parser.parse(new InputSource(new java.io.StringReader(xml)));
        Document doc = parser.getDocument();
        String message = doc.getDocumentElement().getTextContent();
        System.out.println(message);
    } catch (SAXException e) {
        // handle SAXException 
    } catch (IOException e) {
        // handle IOException 
    }
    

    使用 JAXP 接口:

    String xml = "<message>HELLO!</message>";
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = null;
    try {
        db = dbf.newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xml));
        try {
            Document doc = db.parse(is);
            String message = doc.getDocumentElement().getTextContent();
            System.out.println(message);
        } catch (SAXException e) {
            // handle SAXException
        } catch (IOException e) {
            // handle IOException
        }
    } catch (ParserConfigurationException e1) {
        // handle ParserConfigurationException
    }
    

    【讨论】:

    • 你能看到我的question 之一关于 xml 响应吗?
    • @Wayne 你能帮我解决这个问题吗? stackoverflow.com/q/65772815/12953672
    • 导入 java.io.IOException;导入 java.io.StringReader;导入 org.jdom2.Document;导入 org.jdom2.JDOMException;导入 org.jdom2.input.SAXBuilder;公共类 TestXml { public static void main(String[] args) { String xml = "HELLO!"; SAXBuilder saxBuilder = new SAXBuilder();尝试 { 文档文档 = saxBuilder.build(new StringReader(xml));字符串消息 = doc.getRootElement().getText(); System.out.println(消息); } 捕获 (JDOMException e) { } 捕获 (IOException e) { } } }
    【解决方案2】:

    您还可以使用基本 JRE 提供的工具:

    String msg = "<message>HELLO!</message>";
    DocumentBuilder newDocumentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document parse = newDocumentBuilder.parse(new ByteArrayInputStream(msg.getBytes()));
    System.out.println(parse.getFirstChild().getTextContent());
    

    【讨论】:

    • 不要转换为字节,使用 StringReader。
    • 离题但 DocumentBuilder.parse() 只接受一个 InputStream。我只想写最少的示例代码。
    • 不幸的是,最少量的示例代码也是严重错误的。使用默认平台编码将 xml 文本转换为任意字节是破坏上述 xml 的方法。正如您在其他一些答案中看到的那样,您可以使用 InputSource 将 Reader 传递给 DocumentBuilder。
    【解决方案3】:

    您可以使用 JAXB 来做到这一点(Java SE 6 中包含一个实现)。

    import java.io.StringReader;
    import javax.xml.bind.*;
    import javax.xml.transform.stream.StreamSource;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            String xmlString = "<message>HELLO!</message> ";
            JAXBContext jc = JAXBContext.newInstance(String.class);
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            StreamSource xmlSource = new StreamSource(new StringReader(xmlString));
            JAXBElement<String> je = unmarshaller.unmarshal(xmlSource, String.class);
            System.out.println(je.getValue());
        }
    
    }
    

    输出

    HELLO!
    

    【讨论】:

      【解决方案4】:

      上述答案之一表明将 XML 字符串转换为不需要的字节。相反,您可以使用InputSource 并提供StringReader

      String xmlStr = "<message>HELLO!</message>";
      DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      Document doc = db.parse(new InputSource(new StringReader(xmlStr)));
      System.out.println(doc.getFirstChild().getNodeValue());
      

      【讨论】:

        【解决方案5】:

        有做正确的 XML 阅读,或做狡猾的只是为了勉强。 正确的做法是使用正确的文档解析。

        或者...狡猾的人会使用自定义文本解析与 wisuzu 的响应或使用带有匹配器的正则表达式。

        【讨论】:

        • 考虑到用正则表达式解析 (X)HTML,我很高兴将这个答案链接起来;)
        【解决方案6】:

        我想你会看看String 类,有多种方法可以做到这一点。 substring(int,int)indexOf(int) lastIndexOf(int) 呢?

        【讨论】:

        • 对于这样一个简单的例子来说可能是无害的,但通常是处理 XML 的错误方法。
        猜你喜欢
        • 2021-01-13
        • 2016-12-04
        • 2010-11-07
        • 1970-01-01
        • 2012-07-03
        • 1970-01-01
        • 2012-08-01
        • 1970-01-01
        • 2018-08-27
        相关资源
        最近更新 更多